Git Hooks Basics 🪝#

Git hooks are scripts which can be executed after an action is performed, the options are: applypatch-msg, commit-msg, post-update, pre-applypatch, pre-commit, prepare-commit-msg, pre-push, pre-rebase, update.

Git hooks for a given repository are stored under .git/hooks.

 1[~/gitrepo]$ ls .git
 2branches  COMMIT_EDITMSG  config  description  FETCH_HEAD  gitweb  HEAD
 3hooks  index  info  logs  modules  objects  ORIG_HEAD  refs
 4
 5[~/gitrepo]$ cd .git/hooks/
 6
 7[~/gitrepo]$ ls -1
 8
 9applypatch-msg.sample
10commit-msg.sample
11post-update.sample
12pre-applypatch.sample
13pre-commit.sample
14prepare-commit-msg.sample
15pre-push.sample
16pre-rebase.sample
17update.sample

Useful Githook Examples#

Output something to /tmp/ before pushing#

1# create a simple pre-push githook which outputs to /tmp/githook.date.out
2echo 'echo "pre-push" > /tmp/githook.`date +%s`.out' > .git/hooks/pre-push;
3chmod +x ./git/hooks/pre-push

Prevent Pollution of the main Branch#

Although tools like GitLab allow you to protect the main branch in a project against direct pushing, sometimes you may want to do this with bare git repositories.

This pre-commit hook helps guarantee that changes aren’t pushed to main but everything goes through a proper merging processes.

The following git hook prevents such a thing from happening.

1if [ $(git symbolic-ref HEAD 2>/dev/null) == "refs/heads/main" ]
2then
3  echo "Cannot commit to main branch"
4  exit 1
5fi
6exit 0

Taken from https://gist.github.com/shaneog/779e754153ee816ed226