Example Git pre-receive and post-receive Hooks to Avoid a Signal 13 Error

Git has a very nice set of example hooks that you can find just by creating a new repo. The following is an easy way to see them all:

mkdir myrepo
cd myrepo
git init
ls .git/hooks/

If you do that you will end up with a list something like this:

applypatch-msg.sample  post-commit.sample   post-update.sample     pre-commit.sample          pre-rebase.sample
commit-msg.sample      post-receive.sample  pre-applypatch.sample  prepare-commit-msg.sample  update.sample

I recently did this thinking I would create a pre-receive hook. Since there isn't a sample for pre-receive I went to the git hooks reference to see if there was anything special I needed to know. I didn't pay any attention to the fact that git will send something in on STDIN when it runs the hook and as it turns out that is important. In some instances if you don't read STDIN you will get an error message like the following when you try to push and the hook gets used:

fatal: The remote end hung up unexpectedly
error: error in sideband demultiplexer
error:  died of signal 13

The fix for this is to make sure you read STDIN when creating pre-receive and post-receive hooks. The following example shell script will show the commit information for each new revision id when you push and the hook is executed:

while read oldrev newrev refname
  # Do something with $oldrev $newrev $refname 
  git show --no-color --root -s --pretty=medium $newrev

The key part in the above is the "while read" that reads STDIN. So whatever language you write your hook in just make sure you read everything from STDIN before completing the script.

One thought on “Example Git pre-receive and post-receive Hooks to Avoid a Signal 13 Error

  1. Matt McCormick

    You, sir, are a lifesaver! This problem has been driving me nuts for 3 days now! I am using this in a post-receive hook actually. It turns out that your hook does not support the standard input formats that most shell scripting supports (i.e. $1, $2, $3), which is what I was using to assign variables $oldhead, $newhead, etc. And for the life of me, I could not figure out why these were returning empty values. I hope you don't mind, but I will be referencing this post from my blog later tonight.

    Thanks for the help!

Leave a Reply

Your email address will not be published. Required fields are marked *