Ryan Knopp

Using shell script to detect GIT changes.

What I’m trying to accomplish here is having a shell script run and then see if there are any changes to a specific git branch. If there are some changes then do some work. The reason I want a shell script is, so I can put it on a cron job since you can’t do real-time triggers like you can on a git server. My current git server is hosted elsewhere.

Why not use a CI (continuous integration) to do this? I’m cheap 😃. I currently use Bitbucket, and they only give you fifty minutes’ free time and this will probably take longer than that, and I don’t want to be pigeonholed into a specific CI.

Fetch from GIT

So the first thing thing you need to do is a git fetch.

git --git-dir=/path/to/source/.git --work-tree=/path/to/source fetch --quiet

adding in --git-dir and --work-tree will allow you to run this script where ever you want. Doesn’t have to be in the working tree. This will be needed on all git calls.

Detecting changes

So now how do we detect a change from the local branch to a remote branch? We can use git diff.

git --git-dir=/path/to/source/.git --work-tree=/path/to/source diff --quiet origin

So --quet will only output if there are changes otherwise it will return false. origin is the remote server. If you are looking for a specific branch you would do origin/<branch> (ex. origin/staging).

Putting the script together

So now if we put this two lines in a script you get something like.


git --git-dir=/path/to/source/.git --work-tree=/path/to/source fetch --quiet

if ! git --git-dir=$/path/to/source/.git --work-tree=/path/to/source diff --quiet origin
        ## for changes to stick, you need to pull them otherwise it will always have changes
        git --git-dir=/path/to/source/.git --work-tree=/path/to/source pull --quiet
        ## do stuff


Now you can add this to a cronjob and have it execute at any time interval you want. I only have mine trigger during work hours, so I don’t overload the git servers.

Updated: June 15, 2020