What are Git hooks?

Git hooks are scripts that Git executes before or after events such as: commit, push, and receive. Git hooks are a built-in feature - no need to download anything. Git hooks are run locally.

These hook scripts are only limited by a developer’s imagination. Some example hook scripts include:

  • pre-commit: Check the commit message for spelling errors.
  • pre-receive: Enforce project coding standards.
  • post-commit: Email/SMS team members of a new commit.
  • post-receive: Push the code to production.

Why should I care?

Fair question! Git hooks can greatly increase your productivity as a developer. Being able to push to your staging or production environment without ever leaving Git is just plain awesome. Update your code, make a commit and push, and your code can be running in any environment you specify. No need to mess with ssh or ftp.

Git pre-commit example

#!/usr/bin/env bash

# file     : pre-commit
# purpose  : common checks before committing changes
# author   : harald van der laan
# date     : 2018/10/07
# version  : v1.0.0

# check if current local branch is not a rejected branch
declare -a rejected
rejected=(master production)
current=$(git symbolic-ref --short HEAD 2> /dev/null)


for branch in ${rejected}; do
  if [[ "${current}" = "${branch}"]]; then
    echo "[-] pre-commit: ${current} is a rejected branch to commit."
    echo "[-] pre-commit: please undo your changes an us a other branch."
    exit 1

# check is current branch is behind remote origin
git fetch
behind=$(git log --oneline ..@{u} 2> /dev/null | wc -l | tr -d ' ')

if [[ ${behinf} -gt 0 ]]; then
  echo "[-] pre-commit: your local branch is behind of remote origin."
  echo "[-] pre-commit: please git fetch && git pull first."
  exit 1

exit 0