Loading lessons...
Git Hooks
Git Hooks
Hooks are scripts that Git runs automatically at certain moments, like before a commit or after a merge.
Where hooks live
Hooks live in the .git/hooks folder. Git ships with examples like .git/hooks/pre-commit.sample.
Common hooks
| Hook | Runs when |
|---|---|
pre-commit | before a commit is created |
commit-msg | after the message is written |
pre-push | before pushing |
post-merge | after a merge completes |
Example: block bad commits
A pre-commit hook can run your tests and refuse the commit if they fail:
# .git/hooks/pre-commit
if ! npm test; then
echo "Tests failed, commit blocked"
exit 1
fi
Exiting with a non-zero code cancels the operation.
Enable a hook
- Remove the
.sampleextension. - Make the file executable.
- Git runs it automatically from then on.
Note: hooks are local
Hooks live inside .git, so they are not shared with other people unless you use a tool like Husky to sync them.
TL;DR
- Hooks are scripts Git runs at specific moments.
- Common ones: pre-commit, commit-msg, pre-push.
- A non-zero exit code cancels the operation.
- Hooks live in .git/hooks and are not shared by default.