Is there a way to trigger a hook after a new branch has been checked out in Git?

A git hook is a script placed in a special location of your repository, that location is:

.git/hooks

The script can be any kind that you can execute in your environment i.e. bash, python, ruby etc.

The hook that is executed after a checkout is post-checkout. From the docs:

…The hook is given three parameters…

Example:

  1. Create the hook (script):

    touch .git/hooks/post-checkout
    chmod u+x .git/hooks/post-checkout
    
  2. Hook sample content:

#!/bin/bash                                                                      

set -e                                                                           

printf '\npost-checkout hook\n\n'                                                

prevHEAD=$1                                                                      
newHEAD=$2                                                                       
checkoutType=$3                                                                  

[[ $checkoutType == 1 ]] && checkoutType="branch" ||                             
                            checkoutType="file" ;                                

echo 'Checkout type: '$checkoutType                                              
echo '    prev HEAD: '`git name-rev --name-only $prevHEAD`                       
echo '     new HEAD: '`git name-rev --name-only $newHEAD`

Note: The shebang in the first line indicates the type of script.

This script (git hook) will only capture the three parameters passed and print them in a human-friendly format.

Leave a Comment