Execute a Git hook by branch


Many times I’ve been working in several projects when deployment of different webs according to a branch are necessary. Finally I just wrote a tiny Git hook script that helps me out with this matter, I hope it could help you as it does to me.

By example, for branch master I need that every time someone pushes commits to it, changes deploys in /path/to/my/deployment/unstable, and if branch stable is pushed, then changes are deployed in /path/to/my/deployment/stable.

The script I wrote uses the post-update hook, and cut to “parse” the revision name and provide the branch name, then I can use that name to set the path of the repo. After that I check if that directory exists, and then change the GIT_DIR to that path. Finally I change the position to that path and execute a simple git pull specifying the name of the branch.

Feel yourself free to use it. :)

# An example hook script to prepare a packed repository for use over
# dumb transports.
# To enable this hook, rename this file to "post-update".

BRANCH=`echo $1 | cut -d '/' -f 3`

if [ $BRANCH == 'master' ]; then






if [ -d $STAGE_PATH ]; then

 git pull origin $BRANCH


 echo 'Stage path for '$STAGE' not found'


exec git update-server-info


Basilio Briceño

DevOps evangelist, SoftwareLibre activist, sometimes speaker & eclectic metalhead.


  1. fitorec   •  

    Interesante yo ahorita lo que ando buscando es un buen sistema de ganchos que me ayude a actualizar un sitio con la acción post-pull.

    Respecto al script veo que defines una variable STAGE_PATH, creo que el valor de esta lo puedes hacer dinamicamente y con esto reutilizas mas tu script, típicamente yo suelo ocupar la instrucción:

    PATH_SCRIPT = $(readlink -f "$0" | xargs dirname )

    En el caso especifico de git, puedes ocupar:

    git rev-parse --show-toplevel

  2. fitorec   •  

    También puedes ocupar la variable $GIT_DIR.

  3. Basilio Briceño   •  

    Gracias por el comentario, muy buen tip, en este caso puse un path absoluto como ejemplo, por que puede haber casos donde el path sea diferente a la ubicación actual.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>