Git Hooks Explained: Running Checks Before a Commit Lands
Git runs scripts at defined points in its workflow. The useful ones catch a mistake before it becomes a commit, and the thing to understand first is which ones can be skipped.
Where they live
ls -l .git/hooks/
# applypatch-msg.sample
# commit-msg.sample
# pre-commit.sample
# pre-push.sample
# ...
Every repository has sample hooks. They do nothing because of the .sample extension.
# activate one
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
Two requirements: the exact filename, and the execute bit. pre-commit.sh is ignored. A hook without chmod +x is ignored. Both fail silently, which is the single most common reason a hook appears not to work.
# the check to run first, always
ls -l .git/hooks/pre-commit
.git/hooks is not part of the repository. It is not committed, not pushed, and a clone gets only the samples. That is the fact everything else follows from.
The hooks worth knowing
Local, on your machine:
| Hook | Runs | Can reject |
|---|---|---|
pre-commit | Before the message is written | Yes |
prepare-commit-msg | Before the editor opens | No |
commit-msg | After the message is written | Yes |
post-commit | After the commit | No |
pre-rebase | Before a rebase | Yes |
post-checkout | After checkout or clone | No |
post-merge | After a merge | No |
pre-push | Before a push | Yes |
Server-side, where enforcement happens:
| Hook | Runs | Can reject |
|---|---|---|
pre-receive | Once per push, before anything is written | Yes |
update | Once per ref being updated | Yes |
post-receive | After the push succeeds | No |
A non-zero exit from any “can reject” hook stops the operation.
pre-commit, done properly
The mistake is checking the working tree rather than what is being committed.
#!/usr/bin/env bash
# .git/hooks/pre-commit
set -euo pipefail
# only the files actually staged, and only ones that still exist
mapfile -t files < <(git diff --cached --name-only --diff-filter=ACM)
(( ${#files[@]} )) || exit 0
fail=0
# shell scripts
mapfile -t sh < <(printf '%s\n' "${files[@]}" | grep -E '\.(sh|bash)$' || true)
if (( ${#sh[@]} )) && command -v shellcheck >/dev/null; then
shellcheck "${sh[@]}" || fail=1
fi
# leftover debugging
if git diff --cached | grep -nE '^\+.*(console\.log|binding\.pry|import pdb|TODO: ?remove)'; then
echo "debugging statements in staged changes" >&2
fail=1
fi
# merge conflict markers, which get committed more often than you would think
if git diff --cached | grep -nE '^\+(<{7}|>{7}|={7})( |$)'; then
echo "conflict markers in staged changes" >&2
fail=1
fi
exit "$fail"
Three things making this correct:
git diff --cached inspects the staged content, which is what will be committed. Checking the working tree gives wrong answers when you have staged a subset of your changes.
--diff-filter=ACM excludes deleted files, so the hook does not try to lint something that no longer exists.
It exits 0 when nothing relevant is staged. A hook that fails on an empty commit set is a hook people disable.
Our shellcheck guide covers the linter and our error handling guide covers set -euo pipefail.
The staged-versus-working-tree trap
# a formatter that rewrites files needs care
#!/usr/bin/env bash
set -euo pipefail
mapfile -t files < <(git diff --cached --name-only --diff-filter=ACM | grep -E '\.py$' || true)
(( ${#files[@]} )) || exit 0
black --check --quiet "${files[@]}" || {
echo "run black on: ${files[*]}" >&2
exit 1
}
Report rather than rewrite. A hook that reformats files mid-commit commits content you never reviewed, and the staged and working versions diverge in confusing ways. Tell the developer to run the formatter.
commit-msg
#!/usr/bin/env bash
# .git/hooks/commit-msg
set -euo pipefail
msg_file=$1
subject=$(head -1 "$msg_file")
# skip merges and fixups
grep -qE '^(Merge|fixup!|squash!|Revert)' <<< "$subject" && exit 0
if (( ${#subject} > 72 )); then
echo "subject is ${#subject} characters, keep it under 72" >&2
exit 1
fi
if ! grep -qE '^(feat|fix|docs|refactor|test|chore|perf)(\(.+\))?: .+' <<< "$subject"; then
cat >&2 <<'EOF'
subject must look like: type(scope): description
types: feat fix docs refactor test chore perf
EOF
exit 1
fi
Exempt merge and fixup commits. Git generates those messages itself, and a hook that rejects them makes rebasing impossible.
pre-push
The last local gate, and the right place for anything slower.
#!/usr/bin/env bash
# .git/hooks/pre-push
set -euo pipefail
protected='^refs/heads/(main|master|release/.*)$'
while read -r _local_ref local_sha remote_ref _remote_sha; do
# deletion
[[ "$local_sha" == 0000000000000000000000000000000000000000 ]] && continue
if [[ "$remote_ref" =~ $protected ]]; then
echo "direct push to $remote_ref is not allowed, open a pull request" >&2
exit 1
fi
done
pre-push receives the refs being pushed on stdin, one per line, which is why it is a while read loop rather than reading arguments.
Running tests here is more defensible than in pre-commit, because a push is less frequent than a commit and the wait is better tolerated.
Sharing hooks
The problem: hooks are not cloned.
core.hooksPath
mkdir -p .githooks
mv .git/hooks/pre-commit .githooks/
chmod +x .githooks/*
git add .githooks && git commit -m 'add shared hooks'
# each person runs this once
git config core.hooksPath .githooks
# make it discoverable
cat >> README.md <<'EOF'
## Setup
git config core.hooksPath .githooks
EOF
Simple, no dependencies, and it relies on everyone running one command. Some teams put it in a make setup target so it happens as a side effect of something people already do.
pre-commit, the framework
pipx install pre-commit # or pip install --user pre-commit
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-merge-conflict
- id: check-added-large-files
args: ['--maxkb=500']
- id: detect-private-key
- repo: https://github.com/koalaman/shellcheck-precommit
rev: v0.10.0
hooks:
- id: shellcheck
pre-commit install
pre-commit run --all-files
pre-commit autoupdate
detect-private-key and check-added-large-files are worth having on every repository. Both catch mistakes that are painful to undo: a key in git history stays in the commits, as our dotfiles guide notes, and a large binary bloats every clone forever.
The config is tracked, so it is shared. It still needs pre-commit install per clone, which is the same limitation wearing a nicer coat.
Local hooks enforce nothing
Stated plainly, because teams get this wrong.
git commit --no-verify -m 'skipping the hooks'
git push --no-verify
--no-verify skips every local hook, and that is deliberate. Sometimes you genuinely need to commit broken work on a branch nobody else sees.
Which means:
- A local hook is a fast feedback loop, catching a mistake before you notice it in CI twenty minutes later
- It is not a policy control, because the person it constrains can turn it off
Anything that must hold goes server side or in CI:
- Branch protection rules on the forge, which our Gitea versus Forgejo comparison covers for self-hosted options
- Required status checks in CI, per our self-hosted runners guide
pre-receivehooks on a bare repository you control
Server-side hooks
# on the server, in the bare repository
ls -l /srv/git/myrepo.git/hooks/
#!/usr/bin/env bash
# /srv/git/myrepo.git/hooks/pre-receive
set -euo pipefail
while read -r old new ref; do
[[ "$new" == 0000000000000000000000000000000000000000 ]] && continue
# which commits are new
if [[ "$old" == 0000000000000000000000000000000000000000 ]]; then
range=$(git rev-list "$new" --not --all)
else
range=$(git rev-list "$old..$new")
fi
for sha in $range; do
if ! git log -1 --format=%s "$sha" | grep -qE '^(feat|fix|docs|chore): '; then
echo "commit $sha has a bad subject, push rejected" >&2
exit 1
fi
done
done
One non-zero exit rejects the entire push, including the commits that were fine. That is the enforcement property, and it is also why server hooks need to be correct: a bug here blocks everyone.
pre-receive reads old new ref triples on stdin, and the all-zeros hash means a branch being created or deleted.
Hosted forges expose this differently. GitHub has no pre-receive on normal plans and uses branch protection and required checks instead; Gitea and Forgejo let you edit hooks on repositories you administer.
Debugging a hook
# the two causes, in order
ls -l .git/hooks/pre-commit # executable? exact name?
head -1 .git/hooks/pre-commit # shebang present?
# run it by hand, which is the fastest way to see the error
.git/hooks/pre-commit; echo "exit: $?"
# see what git is doing
GIT_TRACE=1 git commit -m test 2>&1 | grep -i hook
# is hooksPath pointing somewhere unexpected
git config --get core.hooksPath
git rev-parse --git-path hooks
Hooks run with the repository root as the working directory and a reduced environment. A hook that works in your shell and fails under git is usually a PATH problem, which our shell startup files guide explains: a hook is a non-interactive shell and reads neither .bashrc nor .profile.
# so use absolute paths, or set PATH in the hook
export PATH="/usr/local/bin:$PATH"
command -v shellcheck >/dev/null || { echo "shellcheck not installed" >&2; exit 0; }
Exit 0 when a tool is missing rather than failing. A hook that breaks commits on a machine lacking an optional linter is a hook that gets deleted.
Frequently Asked Questions
Are git hooks copied when someone clones a repository?
No. Hooks live in the .git/hooks directory, which is not part of the repository contents, so a clone gets the sample files and nothing else. Sharing hooks across a team needs either a tracked directory plus the core.hooksPath setting, or a tool such as pre-commit that installs them.
Can a developer bypass a pre-commit hook?
Yes, with the —no-verify flag, and that is by design. Local hooks are a convenience that catches mistakes early, not a control. Anything that must hold has to be enforced server side or in CI, where the person being checked cannot skip it.
What is the difference between pre-commit and pre-receive?
pre-commit runs on the developer machine before a commit is created and can be skipped. pre-receive runs on the server when a push arrives and rejects the whole push if it exits non-zero. One is a helpful early warning, the other is enforcement.
How do I share hooks with my team?
Commit them to a directory in the repository and point core.hooksPath at it, which each person sets once. Alternatively use a framework such as pre-commit, which reads a tracked config file and manages the hook scripts and their dependencies for you.
Why is my hook not running?
Almost always because it is not executable, or because the filename has an extension. Git looks for a file named exactly pre-commit with the execute bit set, so pre-commit.sh is ignored silently. Check with ls and chmod before looking anywhere else.
Should a pre-commit hook run the full test suite?
No. A hook that takes more than a couple of seconds gets bypassed, and a bypassed hook enforces nothing. Keep local hooks to fast checks such as linting and formatting on changed files only, and leave the full suite to CI where the wait does not block anyone.