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
| Hook | When it runs | Typical use |
|---|---|---|
pre-commit | Before a commit is created | Run linter or tests, find debug code |
commit-msg | After you write the message | Check the message format |
pre-push | Before a push | Run the full test suite |
post-merge | After a merge | Install new dependencies |
post-checkout | After a branch switch | Clean 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.
$ 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.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |