Installing git hooks stored in a project's repository

A project stored on a git repository might have its own useful hooks. These are usually stored in .git/hooks and are not committed to version control.

If these git hooks need to be shared between users then the following method can be used to ease installation for all contributors.

Firstly create a new directory in the repository called git-hooks or similar.

Then place all the git hooks specific to this project into this new directory and commit them to version control as normal.

Installation script

Next, create a script somewhere such as script/ to install the git hooks:

#Installs git hooks from repo into git dir, backing up older versions if different
set -e
echo "Installing git hooks..."
RUN_DATE=`date "+%Y%m%dT%H%M%SZ"`

# Process all git hooks in the directory
for SOURCE in ${SOURCE_DIR}/*; do
SOURCE_NAME=`basename ${SOURCE}`

# If a hook of the same name already exists
if [ -e ${DESTINATION} ]; then

  # If the existing hook is different
  if ! cmp -s ${SOURCE} ${DESTINATION}; then

    # Back it up



The above script will check each file in the git-hooks directory and check if it is installed already for this project. If a different version of a hook is installed it will be backed up first.

This script should be executed by an initial build task such as from make or even by npm as follows.

Installing from NPM

Using the postinstall script with npm we can execute our git hook install script as soon as any packages have been installed. The section of a package.json shown below details this:

"scripts": {
  "postinstall": "script/"

The install script will now be run after npm install has finished.

Last updated: 01/06/2015