Git Hooks

Git hooks are scripts which Git runs automatically when something happens, like before a commit or after a push. You can use them to check your code, run tests, or check commit messages. They live in the folder .git/hooks of each repository.

Common hooks

HookWhen it runsTypical use
pre-commitBefore a commit is createdRun linter or tests, find debug code
commit-msgAfter you write the messageCheck the message format
pre-pushBefore a pushRun the full test suite
post-mergeAfter a mergeInstall new dependencies
post-checkoutAfter a branch switchClean build files

If a “pre” hook exits with a non zero status, Git stops the action.

Create a pre-commit hook

This hook blocks the commit if a staged file contains the word TODO.

#!/bin/sh
# block commit if a staged file has TODO
if git diff --cached | grep -q "^+.*TODO"; then
  echo "Commit blocked: remove TODO comments first."
  exit 1
fi
exit 0

The file must be executable. Then we test it with a file that has a TODO and then a clean one.

Terminal output

$ chmod +x .git/hooks/pre-commit
$ echo "TODO fix price" > price.txt
$ git add price.txt
$ git commit -m "Add price file"
Commit blocked: remove TODO comments first.
$ echo "Price list" > price.txt
$ git add price.txt
$ git commit -m "Add price file"
[main (root-commit) 656eafe] Add price file
1 file changed, 1 insertion(+)
create mode 100644 price.txt

Skip a hook

git commit --no-verify -m "Emergency fix"

Share hooks with the team

The .git/hooks folder is not part of the repository, so hooks are not shared by git push. A common way is to keep the hooks in a normal folder like .githooks inside the project, and tell Git to use it:

git config core.hooksPath .githooks

Tools like Husky (for JavaScript) and pre-commit (for Python) make this easier.

Note: Keep hooks fast. A hook which takes one minute will make people skip it. Next: Git Branching Strategy.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.