Git Hooks
A Git hook is a script that Git runs automatically at a particular moment, such as just before a commit is made, after a checkout, or before a push. Hooks live in .git/hooks/, and each one has a fixed name that says when it runs. If a "pre" hook exits with an error, Git stops the action. Hooks are used to check work before it leaves your hands: run the formatter and tests, reject a commit message that breaks the team's rules, or block an accidental push to main.
A building's front door with an automatic check works the same way: as you walk through, a sensor checks your badge. Most of the time it just lets you in. If something is wrong, the door stays shut and a message tells you why.
Where Hooks Live
Every new repository gets example hooks, with .sample at the end of their names so that they don't run:
mkdir fee-tracker
cd fee-tracker
git init --quiet
ls .git/hooksapplypatch-msg.sample
commit-msg.sample
fsmonitor-watchman.sample
post-update.sample
pre-applypatch.sample
pre-commit.sample
pre-merge-commit.sample
pre-push.sample
pre-rebase.sample
pre-receive.sample
prepare-commit-msg.sample
push-to-checkout.sample
sendemail-validate.sample
update.sampleTo use a hook, create a file without .sample, with the exact hook name, and make it executable. It can be written in any language that can run as a script (a shell script, Python, a small Java launcher), as long as the first line names the interpreter.
The Most Useful Client-Side Hooks
| Hook | Runs | Can stop the action? | Typical use |
|---|---|---|---|
pre-commit | Before the commit message is asked for | Yes | Format, lint, quick tests, check for secrets or debug code |
prepare-commit-msg | Before the editor opens, with the default message | Yes | Fill in a template, add the issue number from the branch name |
commit-msg | After the message is written | Yes | Enforce a message format, such as Conventional Commits |
post-commit | After the commit is made | No | Notifications |
pre-push | Before anything is sent | Yes | Run the full test suite, block pushes to protected branches |
post-checkout | After git switch, git checkout or git clone | No | Clean build output, update dependencies |
post-merge | After a successful merge or pull | No | Reinstall dependencies when the build file changed |
pre-rebase | Before a rebase starts | Yes | Refuse to rebase certain branches |
A hook "stops" an action by exiting with a non-zero code. Anything it prints is shown to you, which is how it explains the refusal.
Example 1: A pre-commit Hook
Navika keeps forgetting System.out.println("DEBUG ...") lines. A pre-commit hook can look at the staged changes and refuse the commit if any added line contains DEBUG. It also runs git diff --cached --check, which catches trailing spaces and leftover conflict markers:
cat > .git/hooks/pre-commit <<'EOF'
#!/bin/sh
# Refuse commits that add debug output or whitespace errors.
if git diff --cached -U0 | grep -q "^+.*DEBUG"; then
echo "pre-commit: remove DEBUG lines before committing."
exit 1
fi
exec git diff --cached --check
EOF
chmod +x .git/hooks/pre-commit
echo 'class Fees { void show() { System.out.println("DEBUG fees"); } }' > Fees.java
git add Fees.java
git commit -m "Add the fees class"pre-commit: remove DEBUG lines before committing.Explanation: the hook found an added line with DEBUG, printed its reason and exited with 1, so Git didn't create the commit. The change is still staged. Navika removes the debug line and commits again:
echo 'class Fees { int total() { return 12000; } }' > Fees.java
git add Fees.java
git commit --quiet -m "feat: add the fees class"
git log --oneline053d7d5 (HEAD -> main) feat: add the fees classThe hook found nothing, so the commit went through. -U0 gave a diff without context lines, so that only the changed lines are searched, and exec made the hook's exit code that of git diff --check.
Example 2: A commit-msg Hook
The team uses Conventional Commits ("Writing Good Commit Messages"). The commit-msg hook receives the path of a file holding the message as its first argument ($1), and can check it:
cat > .git/hooks/commit-msg <<'EOF'
#!/bin/sh
# Require Conventional Commits: type(optional scope)!: description
pattern='^(feat|fix|docs|refactor|test|chore)(\([a-z-]+\))?!?: .+'
if ! head -1 "$1" | grep -Eq "$pattern"; then
echo "commit-msg: start the subject with a type, such as 'feat: ' or 'fix: '."
exit 1
fi
EOF
chmod +x .git/hooks/commit-msg
echo 'Late fee: $250' > fees.txt
git add fees.txt
git commit -m "Add the late fee"commit-msg: start the subject with a type, such as 'feat: ' or 'fix: '.The subject has no type, so the hook refused it. With a proper subject:
git commit --quiet -m "feat(fees): add the late fee"
git log --oneline -1b89cd1f (HEAD -> main) feat(fees): add the late feeExample 3: A pre-push Hook
A pre-push hook receives the remote's name and URL as arguments, and on its input one line per ref being pushed: <local ref> <local id> <remote ref> <remote id>. This one refuses direct pushes to main:
git init --bare --quiet ../fee-tracker.git
git remote add origin ../fee-tracker.git
cat > .git/hooks/pre-push <<'EOF'
#!/bin/sh
while read local_ref local_id remote_ref remote_id; do
if [ "$remote_ref" = "refs/heads/main" ]; then
echo "pre-push: don't push to main directly. Push a branch and open a pull request."
exit 1
fi
done
EOF
chmod +x .git/hooks/pre-push
git push origin mainpre-push: don't push to main directly. Push a branch and open a pull request.
error: failed to push some refs to '../fee-tracker.git'The hook stopped the push before anything was sent: failed to push some refs. Pushing a branch is allowed:
git switch --quiet -c feature/hostel-fee
git push --quiet origin feature/hostel-fee
git ls-remote --heads originb89cd1f0c2b9cdd15175e4eea3f8a951f167fb9d refs/heads/feature/hostel-feeSkipping Hooks: --no-verify
pre-commit and commit-msg hooks can be skipped with --no-verify (or -n) on git commit, and pre-push with --no-verify on git push:
echo 'Hostel fee: $9,000' >> fees.txt
git commit --quiet --no-verify -am "quick fix"
git log --oneline -12bb3d5b (HEAD -> feature/hostel-fee) quick fixThe badly formatted message got through, because the hooks didn't run. That is useful for an emergency, but it means local hooks are a convenience, not a guarantee: anyone can skip them, and a fresh clone has none at all. The rules that really matter must also be checked on the server, by CI and branch protection (see "Git and CI/CD").
Server-Side Hooks
The server copy of a repository can have hooks too. They run when someone pushes, so nobody can skip them:
| Hook | Runs | Can refuse? | Typical use |
|---|---|---|---|
pre-receive | Once per push, before any ref is updated | Yes, the whole push | Enforce rules for all branches |
update | Once per ref being pushed | Yes, that ref only | Per-branch permissions |
post-receive | After all refs are updated | No | Notify a chat, start a deployment |
cat > ../fee-tracker.git/hooks/pre-receive <<'EOF'
#!/bin/sh
zero=0000000000000000000000000000000000000000
while read old new ref; do
# A new branch has no old commit: check only commits the server doesn't have yet.
if [ "$old" = "$zero" ]; then range="$new --not --all"; else range="$old..$new"; fi
if git log --format=%s $range | grep -qi "^quick fix"; then
echo "Rejected: a commit on $ref has the message 'quick fix'. Please reword it."
exit 1
fi
done
EOF
chmod +x ../fee-tracker.git/hooks/pre-receive
git push origin feature/hostel-feeremote: Rejected: a commit on refs/heads/feature/hostel-fee has the message 'quick fix'. Please reword it.
To ../fee-tracker.git
! [remote rejected] feature/hostel-fee -> feature/hostel-fee (pre-receive hook declined)
error: failed to push some refs to '../fee-tracker.git'Explanation: the server ran its pre-receive hook for the new commits on feature/hostel-fee, found the "quick fix" commit that Navika had made with --no-verify, and refused the push. For a branch that is new on the server, the "old" ID is all zeros, so the hook then checks only the commits the server doesn't have yet (--not --all). Its output reached Navika with remote: in front. On GitHub, GitLab and Bitbucket, you can't install your own server-side hooks on hosted repositories. Protected branches, push rules and required checks play that role there. Self-hosted servers (GitLab Self-Managed, Bitbucket Data Center, plain Git servers) support them.
Common Mistakes
Forgetting chmod +x. A hook that isn't executable is silently ignored (Git prints a hint about it on some systems).
Keeping .sample in the name. Only the exact hook name runs.
Slow hooks. A pre-commit hook that runs the whole test suite makes people use --no-verify. Keep it to seconds, and put the full suite in pre-push or CI.
Checking the working tree instead of the staged content. Files may have unstaged changes. Check git diff --cached, or what will actually be committed.
Expecting hooks to be cloned. .git/hooks/ is never pushed or cloned. "Sharing Hooks with a Team" shows how to share them.
Under the Hood
Before each hookable action, Git looks for an executable with the hook's name in the hooks folder (.git/hooks/, or the folder named by core.hooksPath). If it exists, Git runs it with the repository's top folder as the current folder (or the .git folder for some server hooks), passes arguments and standard input as each hook's documentation describes (git help githooks), and checks the exit code. On Windows, Git for Windows runs shell-script hooks with its bundled Bash, so the same scripts work on every operating system.
Interview Corner
What are Git hooks?
Scripts that Git runs automatically at certain points, such as pre-commit, commit-msg and pre-push on the client, or pre-receive and post-receive on the server. A non-zero exit from a "pre" hook aborts the action.
Where are hooks stored, and are they shared through Git?
In .git/hooks/ (or the folder set by core.hooksPath). They are not committed, pushed or cloned, so teams share them by committing a hooks folder and setting core.hooksPath, or with a hook manager.
How do you bypass a commit hook?
git commit --no-verify (or -n) skips pre-commit and commit-msg. git push --no-verify skips pre-push. Because of this, important rules must also be enforced by CI and server-side checks.
What is the difference between pre-commit and commit-msg?
pre-commit runs before the message is written and checks the staged content. commit-msg runs after the message is written, receives the message file's path, and checks or edits the message.
What are server-side hooks used for?
pre-receive and update can reject pushes that break rules for everyone, and post-receive triggers actions after a push, such as notifications or deployments. On hosted platforms, protected branches, push rules and CI take their place.
Practice
Challenge: a hook that adds the issue number. The team's branches are named like fix/142-rounding. Write a prepare-commit-msg hook that adds Refs #142 (the number from the branch name) as the last line of every commit message, then commit on such a branch and print the full message.
What does Git print? Before you open the solution, decide which argument tells the hook where the message is, and which command finds the branch name.
Show solution
cat > .git/hooks/prepare-commit-msg <<'EOF'
#!/bin/sh
issue=$(git symbolic-ref --short HEAD | sed -n 's#^[a-z]*/\([0-9][0-9]*\)-.*#\1#p')
if [ -n "$issue" ]; then
printf "\nRefs #%s\n" "$issue" >> "$1"
fi
EOF
chmod +x .git/hooks/prepare-commit-msg
git switch --quiet -c fix/142-rounding
echo "Totals are rounded." >> fees.txt
git commit --quiet -am "fix: round the totals"
git log -1 --format=%Bfix: round the totals
Refs #142The hook read the branch name with git symbolic-ref --short HEAD, extracted 142, and appended Refs #142 to the message file ($1) before the commit was made. The commit-msg hook still checked the subject, which passed.
Checkpoint. In a practice repository, add a pre-commit hook that runs your formatter or mvn -q spotless:check (if your project uses Spotless), and a commit-msg hook that enforces Conventional Commits. Try to break each rule once, and once use --no-verify.
Key Takeaways
Quick reference
| Item | It is used to |
|---|---|
.git/hooks/<name> | Install a hook (executable, exact name) |
chmod +x .git/hooks/<name> | Make it runnable |
git diff --cached --check | Find whitespace errors in staged changes |
git commit --no-verify | Skip pre-commit and commit-msg |
git push --no-verify | Skip pre-push |
git help githooks | Read every hook's arguments and rules |
Was this tutorial helpful?