Everyone is welcome, everyone can contribute, everyone is unique and these are your strengths too!

Bash script for checking out the master branch of many repositories in a directory

So I already posted this in my blog but as very few people read that :), I thought I’d post it here too.

When dealing with microservices, sometimes I’ve found myself needing to go through all the repositories for a project in a folder and checkout the most recent master so it can be deployed. Again the other day I had to do this so I finally wrote a script to make it go a bit faster. If there are changes in your working tree, it will notify at the end so you don’t have to worry about losing changes in any repos.

#!/bin/bash

REPOSITORIES=${PWD}
RED='\033[0;31m'
NC='\033[0m' # No Color
IFS=$'\n'
MANUAL_UPDATE_REPOS=()

for REPO in `ls "$REPOSITORIES/"`
do
  if [ -d "$REPOSITORIES/$REPO" ]
  then
    echo "Updating $REPOSITORIES/$REPO at `date`"
    if [ -d "$REPOSITORIES/$REPO/.git" ]
    then
      cd "$REPOSITORIES/$REPO"
      repo_status=$(git status)
      if [[ $repo_status != *"nothing to commit, working tree clean"* ]] 
      then
        echo -e "You need to stash or commit your code before this repository ${RED}$REPO${NC} can be set to master"
        MANUAL_UPDATE_REPOS+=($REPO)
      else
        echo "Fetching from remote"
        git fetch
        echo "Checking out master"
        git checkout master
        echo "Pulling"
        git pull
      fi
    else
      echo "Skipping because it doesn't look like it has a .git folder."
    fi
    echo "Done at `date`"
  fi
done
echo "These repos:"
printf "${RED}%s${NC}\n" ${MANUAL_UPDATE_REPOS[@]}
echo "do not have clean working trees and master cannot be checked out."
Date published: July 1, 2020