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
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:
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.
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:
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.