Git Hooks: pre-commit, commit-msg, pre-push, Server-Side Hooks and Sharing Hooks
Run checks automatically at key moments with Git hooks: how hook scripts work, pre-commit, commit-msg and pre-push examples, bypassing with --no-verify, server-side pre-receive hooks, sharing hooks with core.hooksPath and frameworks, and Git 2.54's hooks defined in configuration.
kvi5hnuCode Sprout team member7 min readOn this page
A hook is a program Git runs automatically at a particular moment: before a commit is created, after a checkout, before a push is sent, when a server receives a push. If certain hooks exit with an error, Git stops the operation. That makes hooks the place for quick automatic checks: formatting, linting, commit message rules, blocking pushes to the wrong branch. This article shows how they work, with examples you can adapt.
How hooks work
Hooks live in .git/hooks/, one file per hook, named exactly after the hook (pre-commit, commit-msg, ...), with no extension, and executable. New repositories contain examples ending in .sample, which are inactive. A hook can be written in any language that can run as a script: shell, Python, Node.js and so on, with a #! line saying which.
| Hook | Runs | Can stop the operation? |
|---|---|---|
pre-commit | before the commit message is asked for | yes |
prepare-commit-msg | before the editor opens, with the message file | yes |
commit-msg | after the message is written, with the message file | yes |
post-commit | after the commit is made | no |
pre-rebase | before a rebase starts | yes |
post-checkout, post-merge | after a checkout or switch, after a merge | no |
pre-push | before a push sends anything | yes |
pre-receive, update, post-receive | on the server, when a push arrives | the first two can |
Hooks are not copied by git clone and aren't part of the repository's history, because a cloned repository could otherwise run any program on your machine. Sharing them takes an explicit step, covered below.
pre-commit: check what's being committed
git init -q trail-guide && cd trail-guide
cat > .git/hooks/pre-commit <<'EOF'
#!/bin/sh
# Refuse whitespace errors in the staged changes
git diff --cached --check || exit 1
# Refuse a marker that should never be committed
if git diff --cached -U0 | grep -q '^+.*DO NOT COMMIT'; then
echo "pre-commit: remove 'DO NOT COMMIT' before committing" >&2
exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
echo "Lake loop: 5 km" > lake.txt
echo "debug: DO NOT COMMIT" >> lake.txt
git add lake.txt
git commit -q -m "Add lake page"; echo "exit status $?"
sed -i '/DO NOT COMMIT/d' lake.txt; git add lake.txt
git commit -q -m "Add lake page"; echo "exit status $?"
git log --oneline
pre-commit: remove 'DO NOT COMMIT' before committing
exit status 1
exit status 0
65a5265 Add lake page
- A hook that exits with a non-zero status stops the commit. Its output, especially on standard error, is shown to you.
- Check the staged content (
git diff --cached), not the working tree, because that's what will be committed. - Keep pre-commit hooks fast: a hook that takes 30 seconds makes people skip it. Run the full test suite in CI instead.
commit-msg: enforce a message format
commit-msg receives one argument: the path of the file containing the message. It can check the message, or even edit it:
git init -q trail-guide && cd trail-guide
cat > .git/hooks/commit-msg <<'EOF'
#!/bin/sh
# Require messages like "feat: ...", "fix: ...", "docs: ..."
first=$(head -n 1 "$1")
if ! echo "$first" | grep -qE '^(feat|fix|docs|refactor|test|chore)(\(.+\))?!?: .+'; then
echo "commit-msg: start the subject with a type, such as 'fix: correct lake distance'" >&2
exit 1
fi
EOF
chmod +x .git/hooks/commit-msg
git commit -q --allow-empty -m "Updated stuff"; echo "exit status $?"
git commit -q --allow-empty -m "docs: describe the lake loop"; echo "exit status $?"
git log --format=%s
commit-msg: start the subject with a type, such as 'fix: correct lake distance'
exit status 1
exit status 0
docs: describe the lake loop
This enforces the Conventional Commits style (article 52). prepare-commit-msg is the related hook for filling in the message, such as adding a ticket number taken from the branch name.
pre-push: last check before sharing
pre-push receives the remote's name and URL as arguments, and on standard input one line per reference being pushed: <local ref> <local id> <remote ref> <remote id>.
git init -q --bare server.git
git clone -q server.git sam 2>/dev/null; cd sam
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, open a pull request" >&2
exit 1
fi
done
EOF
chmod +x .git/hooks/pre-push
git commit -q --allow-empty -m "Start project"
git push -q origin main; echo "push to main: exit $?"
git switch -q -c lake-page
git push -q -u origin lake-page; echo "push to lake-page: exit $?"
pre-push: don't push to main directly, open a pull request
error: failed to push some refs to '/workspace/server.git'
push to main: exit 1
push to lake-page: exit 0
Pre-push hooks suit slower checks than pre-commit, such as running unit tests, since they run less often.
Skipping hooks: --no-verify
git commit --no-verify (-n) skips pre-commit and commit-msg, and git push --no-verify skips pre-push. That's useful for a work-in-progress commit, and it's also why client-side hooks are a convenience, not enforcement: anyone can skip them, or simply not install them. Rules that must hold belong on the server or in CI.
To skip the hooks folder for one command, use git -c core.hooksPath=/dev/null <command>. It doesn't affect configuration-based hooks (Git 2.54): use --no-verify where the command supports it, or hook.<name>.enabled=false.
Server-side hooks
On a server that hosts bare repositories, hooks in the repository's hooks/ folder run when pushes arrive:
pre-receiveruns once per push, with all the updated references on standard input. Exiting non-zero rejects the whole push.updateruns once per reference, with the reference name and old and new IDs as arguments, and can reject individual references.post-receiveruns after the update, for notifications, deployments or triggering CI.
Their output is relayed to the person pushing, prefixed with remote::
git init -q --bare server.git
cat > server.git/hooks/pre-receive <<'EOF'
#!/bin/sh
zero=0000000000000000000000000000000000000000
while read old new ref; do
[ "$new" = "$zero" ] && continue # a deletion
range=$new; [ "$old" != "$zero" ] && range="$old..$new"
for big in $(git rev-list --objects $range | cut -d' ' -f1 |
git cat-file --batch-check='%(objecttype) %(objectsize) %(objectname)' |
awk '$1 == "blob" && $2 > 100000 {print $3}'); do
echo "Rejected: a file over 100 kB ($big). Use Git LFS for large files." >&2
exit 1
done
done
EOF
chmod +x server.git/hooks/pre-receive
git clone -q server.git sam 2>/dev/null; cd sam
git commit -q --allow-empty -m "Start project"; git push -q origin main; echo "first push: exit $?"
head -c 200000 /dev/zero > video.bin; git add .; git commit -q -m "Add video"
git push origin main 2>&1 | grep -E "remote:|rejected"
first push: exit 0
remote: Rejected: a file over 100 kB (bf5aa3c5d5cacc765dc99d06c4a699bc44f045a9). Use Git LFS for large files.
! [remote rejected] main -> main (pre-receive hook declined)
Hosting services don't let you install arbitrary server hooks on their shared servers. Instead they offer the same controls as settings, such as branch protection, required status checks, push rules and file size limits, and webhooks that call your own service after a push, the equivalent of post-receive. Self-hosted GitLab and Gitea installations do allow server hooks.
Sharing hooks with a team
Since hooks aren't cloned, teams use one of these approaches:
core.hooksPath points Git at a folder of hooks, which can be committed to the repository:
mkdir .githooks # committed, with executable hook scripts inside
git config core.hooksPath .githooks # each developer runs this once
Many projects run that git config line from their setup script, or from a package manager step such as npm install.
Hook frameworks manage installation and running for you:
- pre-commit (Python-based, language-independent) reads a
.pre-commit-config.yamllisting checks from a large catalogue of formatters and linters, and installs itself withpre-commit install. - Husky and lint-staged are popular in JavaScript projects. Lefthook is a fast, language-independent alternative.
Hooks in configuration (Git 2.54)
Since Git 2.54, hooks can also be defined in configuration, which allows several commands for the same event, and hooks set centrally in global or system configuration:
git init -q trail-guide && cd trail-guide
git config set hook.whitespace.command 'git diff --cached --check'
git config set hook.whitespace.event pre-commit
git config set hook.greeting.command 'echo "greeting hook: about to commit"'
git config set hook.greeting.event pre-commit
printf '#!/bin/sh\necho "hooks folder: pre-commit"\n' > .git/hooks/pre-commit; chmod +x .git/hooks/pre-commit
git hook list --show-scope pre-commit
echo "Lake loop " > lake.txt; git add . # trailing spaces
git commit -q -m "Add lake page"; echo "exit status $?"
git config set hook.whitespace.enabled false
git commit -q -m "Add lake page"; echo "exit status $?"
local whitespace
local greeting
hook from hookdir
lake.txt:1: trailing whitespace.
+Lake loop
greeting hook: about to commit
hooks folder: pre-commit
exit status 1
greeting hook: about to commit
hooks folder: pre-commit
exit status 0
hook.<name>.commandis the command, andhook.<name>.eventthe hook it runs for.eventcan be given several times.- Configured hooks run in the order they're defined, before the script in the hooks folder, and receive the same arguments and input. Every hook for the event runs, and the operation fails if any of them fails, as in the output above.
hook.<name>.enabled falseturns one off, for example in a single repository when it's set globally.- Since Git 2.55, hooks for an event can run in parallel, with
hook.jobsorhook.<event>.jobsandhook.<name>.parallel. git hook list <event>shows what will run, including "hook from hookdir" for a script in the hooks folder, andgit hook run <event>runs them by hand.
What's current
- Configuration-based hooks (Git 2.54), with parallel execution (Git 2.55), make several hooks per event possible without a framework.
- Setting
core.hooksPath=/dev/nulldisables the hooks folder, as the Git 2.50 documentation describes. That predates configuration-based hooks, which it doesn't disable. - Hook frameworks such as pre-commit, Husky and Lefthook remain the common way to share checks in a team.
- Enforcement lives in CI and the hosting service's branch rules. Client hooks give fast feedback.
Common questions
I created .git/hooks/pre-commit, but it doesn't run. Why?
Usually it isn't executable: run chmod +x .git/hooks/pre-commit. Also check that the name has no extension (pre-commit, not pre-commit.sh), that #! names an existing interpreter, and that core.hooksPath isn't pointing elsewhere: git config get core.hooksPath.
Can hooks be committed so everyone gets them?
Not into .git/hooks, which isn't versioned. Commit a folder such as .githooks/ and have everyone set core.hooksPath to it, or use a framework like pre-commit or Husky.
Do hooks run during a rebase or cherry-pick?
Partly. When a rebase or cherry-pick replays commits unchanged, pre-commit and commit-msg don't run, but post-commit runs for each new commit. When you reword a commit in rebase -i, both pre-commit and commit-msg run for it. post-checkout runs when the rebase starts, and post-rewrite once at the end, and after commit --amend.
Why did my push fail with remote: ... and pre-receive hook declined?
A server-side hook rejected it. The remote: lines are its explanation, such as a file being too large, or a protected branch.
Summary
- Hooks are executable scripts in
.git/hooks/, named after the event. A non-zero exit from apre-*hook orcommit-msgstops the operation. pre-commitchecks staged content,commit-msgchecks the message, andpre-pushchecks what's being pushed.--no-verifyskips client hooks, so they're helpers. Enforce rules on the server or in CI.- Server-side
pre-receiveandupdatecan reject pushes, andpost-receivereacts to them. Hosting services offer branch rules and webhooks instead. - Share hooks with
core.hooksPathor a framework. Since Git 2.54,hook.<name>.commandand.eventdefine hooks in configuration.
Practice questions
Write a pre-commit hook that stops commits containing whitespace errors in staged changes.
Answer
#!/bin/sh
exec git diff --cached --check
Save it as .git/hooks/pre-commit and make it executable. git diff --cached --check prints the problems and exits with a non-zero status when there are any, which stops the commit.
Your team's pre-commit hook is in tools/hooks/pre-commit in the repository. How does each developer enable it?
Answer
git config core.hooksPath tools/hooks, once per clone. Make sure the file is executable and committed that way (git update-index --chmod=+x tools/hooks/pre-commit if needed). Many projects put the git config line in their setup script.
Why can't a client-side pre-push hook guarantee that nobody pushes to main?
Answer
Client hooks run only on machines where they're installed, and anyone can bypass them with git push --no-verify or by not installing them. To guarantee it, protect main on the hosting service, or use a server-side pre-receive or update hook on a self-hosted server.
Previous: Line Endings and .gitattributes: autocrlf, eol, Binary Files and Diff Drivers
Next: Git Tooling: Shell Prompt and Completion, GUI Clients, and External Diff and Merge Tools

More in Git Course
Quiz: Git Delicate Details
Twenty-five questions on Git's subtle corners: what commit -a and stash leave out, empty folders, ignore patterns and negation, HEAD~ versus HEAD^, ours and theirs in a rebase, tags that don't move or don't push, describe, merge reverts, diff exit codes, stash conflicts and more.
Quiz: Git Interview Questions
Thirty Git questions of the kind asked in developer interviews: Git versus GitHub, the staging area, merge versus rebase, fetch versus pull, reset, revert and restore, detached HEAD, conflicts, force pushing, stash, cherry-pick, reflog, bisect, submodules, LFS and how commits are identified.
Quiz: Git Course Final Exam (All Parts)
The final exam for the Git course: thirty questions across all twelve parts, from the three areas and staging through branching, remotes, undoing, history investigation, configuration, tags, larger projects, patches, rewriting, internals and troubleshooting.
Quiz: Professional Git Practice (Git Part 12)
Sixteen questions on migrating to Git from Subversion, TFVC and Mercurial, team best practices for commits, branches and reviews, repository hygiene, and diagnosing and fixing the most common Git errors, with explanations.
Discussion
Sign in to ask a question or share what you learned.