Last Updated: March 02, 2018
· mike360

Git post-receive hook to checkout a specific branch

If you deploy using a git post-receive hook, this script will allow you to push and checkout a specific branch on your remote rather than only being able to use master.

Create myrepo.git/hooks/post-receive:


while read oldrev newrev ref
    branch=`echo $ref | cut -d/ -f3`
    GIT_WORK_TREE=/path/to/local/checkout git checkout -f $branch

chmod +x myrepo.git/hooks/post-receive`

From your local checkout:

git push myremote mybranch

4 Responses
Add your response

Is there a way to check out 2 branches master and develop, to there own directories?
master to /sites/live/site/
develop to /sites/dev/site/

over 1 year ago ·

@myserioushunt sorry I just saw this comment. Not sure how long you've been waiting for an answer. I would approach it from a standpoint of having two separate git remotes on the same server. So you could have myrepo-production.git and myrepo-develop.git. Alter the paths in the post receive hook for each remote accordingly. Then you would be able to git push production mybranch and git push develop mybranch.

over 1 year ago ·

Branch name may contain slashes, so it should be:
branch=`echo $ref | cut -d/ -f3-`

over 1 year ago ·

This hook is a thing of beauty.

Really well done. Thanks!

over 1 year ago ·