Helpful Bash Script - git reset all

22 Sep 2021

I use this script at work and at home. It saves me a lot of time when I need all of my local repositories to be up to date with the master branch.

It’s a simple script - it iterates through a folder (in my case, ~/Documents) and checks each directory to see if it’s a valid git project. If so, it checks out master and fetches the latest commits. Optionally, you can also have the script delete all branches other than master. You can also (again, optionally) run yarn install in any directories with a yarn.lock file.

If you go on vacation for a week and come back to all of your repositories out-of-date, this script is a lifesaver.



# Ensure we're in the correct directory (update this directory to your preference)
cd ~/Documents

# Loop through each sub-directory and perform some work on them
for f in *; do

    if [ -d "$f" ]; then

        # Ignore this directory when making changes
        if [ "$f" == $IGNORED_DIRECTORY ]; then
            echo "Ignoring $IGNORED_DIRECTORY"
            continue 1

        cd "$f" # $f is a directory, so we can cd into it

        if [ -d .git ]; then
            # This directory has a .git directory :)
            git reset --hard
            git clean -d -f
            git checkout master
            git pull

            ### Warning: This will delete ALL local branches aside from master!
            # Only uncomment if you really, really want this!
            # git branch | grep -v "master" | xargs git branch -D

            ### Warning: This installs all yarn packages in all directories
            # Very slow, but very useful!
            # if [ -f yarn.lock ]; then
            #     echo "yarn.lock exists, installing packages."
            #     yarn install
            # fi

            echo "/${f}/ does not have a .git directory."

        cd ..