Git

Shell script to update all Git repositories at once

  • dani

dani

1 min read
Photo by Yancy Min / Unsplash

Assume you clone all your Git repositories into the same local directory on your computer, e.g. ~/mygitrepos. It can be a mess to update all the Git repositories especially if you divided a larger software project into several smaller Git repositories.

To update all the repositories in one directory at once, you can use the below shell script. It traverses all subdirectory of the current working directory, i.e. the directory from where it is called. Therefore, you can also place it in /usr/local/bin/ or alike and call it from there in any directory.

The script has two update modes: fetch and pull. The modes literally determine if the script should call git fetch or git pull to update your repositories.

#!/bin/bash
usage ()
{
        echo "Usage: $(basename "$0") [mode]"
        echo "  Options:"
        echo "         - mode: fetch or pull"
}
function error_exit ()
{
        echo "$1" 1>2
        usage
        exit 1
}
WORKING_DIRECTORY=`pwd`
echo "Updating all repositories in ${WORKING_DIRECTORY}"
if [ -z "$1" ]
then
        echo "No mode provided. Using default mode."
        MODE="fetch"
elif    [ "$1" = "pull" ]
then
        MODE="pull"
elif [ "$1" = "fetch" ]
then
        MODE="fetch"
else
        error_exit "ERROR: unknown mode $1"
fi
LOGFILE="${WORKING_DIRECTORY}/gitupdateall.log"
echo "Using mode: $MODE"
echo "Using logfile: $LOGFILE"
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && if [ -d '.git' ]; then echo 'Found git repository:'; pwd; echo 'Updating..'; git $MODE -v >> $LOGFILE 2>&1; echo 'Done.'; fi;"; \;

You can also find the script on my GitHub page at https://github.com/danieldinter/shell-misc/blob/master/gitupdateall.sh.