Check for changes on remote origin Git repository in shell script

Check for changes on remote origin Git repository in shell script

In a build shell script I use I needed to check for changes on the remote of a git repo to make sure I’m deploying the latest version. To do that I use Git rev-parse. You could probably do this better and in some other way. But this worked for me.

To be more specific: I need to check if there are more changes/commits on the origin master than I have on my local machine. This is all done in a shell-script.

The script I’m adding this to is the one found in the switching to Jekyll post.

1. Check if on master

Before starting I want to check so that I have the master branch checked out. Since thats the branch i want to deploy from. You could do this with rev-parse –abbrev-ref head

git rev-parse --abbrev-ref HEAD

This would return master if on master branch. I could do a git branch but that would return a list of branches with the currently selected marked with a *. So this saves me from string manipulations.

Putting together a shell script that checks if you have master branch checked out could look like this:

 #!/bin/bash
 ACTION='\033[1;90m'
 FINISHED='\033[1;96m'
 READY='\033[1;92m'
 NOCOLOR='\033[0m' # No Color
 ERROR='\033[0;31m'

 echo
 echo -e ${ACTION}Checking Git repo
 echo -e =======================${NOCOLOR}
 BRANCH=$(git rev-parse --abbrev-ref HEAD)
 if [ "$BRANCH" != "master" ]
 then
   echo -e ${ERROR}Not on master. Aborting. ${NOCOLOR}
   echo
   exit 0
 fi
 

2. Git fetch

Now it is time to do a git fetch to download objects and refs from our remote master without merging anything to our local branch.

After that we can get the latest commit hash from our branch by running git rev-parse HEAD. Then to get the latest commit hash from the origin we run git rev-parse master@{upstream} and compare these two. If they do not match there is either changes in the origin master, or you haven’t pushed the latest local commit to origin master.

 #color variables here...

 git fetch
 HEADHASH=$(git rev-parse HEAD)
 UPSTREAMHASH=$(git rev-parse master@{upstream})

 if [ "$HEADHASH" != "$UPSTREAMHASH" ]
 then
   echo -e ${ERROR}Not up to date with origin. Aborting.${NOCOLOR}
   echo
   exit 0
 else
   echo -e ${FINISHED}Current branch is up to date with origin/master.${NOCOLOR}
 fi
 

3. Using ls-remote instead

If you have a large repo you could probably use ls-remote like this git ls-remote origin -h refs/heads/master which would return something like this:

fc94529726cf4c06039815bs447496b6768a6b94        refs/heads/master

But you would need to remove everything after the hash some way, not covered here, but hopefully you can continue yourself if you want to use it.

4. Thanks

Thanks to multiple Stack overflow threads for helping out. The Git documentation is hard to understand sometimes.