Writing a git post-receive hook to deal with a specific branch Writing a git post-receive hook to deal with a specific branch git git

Writing a git post-receive hook to deal with a specific branch


A post-receive hook gets its arguments from stdin, in the form:

<oldrev> <newrev> <refname>

Since these arguments are coming from stdin, not from a command line argument, you need to use read instead of $1 $2 $3.

The post-receive hook can receive multiple branches at once (for example if someone does a git push --all), so we also need to wrap the read in a while loop.

A working snippet looks something like this:

#!/bin/bashwhile read oldrev newrev refnamedo    branch=$(git rev-parse --symbolic --abbrev-ref $refname)    if [ "master" = "$branch" ]; then        # Do something    fidone


The last parameter that a post-receive hook gets on stdin is what ref was changed, so we can use that to check if that value was "refs/heads/master." A bit of ruby similar to what I use in a post-receive hook:

STDIN.each do |line|    (old_rev, new_rev, ref_name) = line.split    if ref_name =~ /master/         # do your push    endend

Note that it gets a line for each ref that was pushed, so if you pushed more than just master, it will still work.


Stefan's answer didn't work for me, but this did:

#!/bin/bashecho "determining branch"if ! [ -t 0 ]; then  read -a reffiIFS='/' read -ra REF <<< "${ref[2]}"branch="${REF[2]}"if [ "master" == "$branch" ]; then  echo 'master was pushed'fiif [ "staging" == "$branch" ]; then  echo 'staging was pushed'fiecho "done"