Git Hooks Explained: Pre-commit and Commit-msg Scripts That Work
Git hooks are scripts Git runs automatically at moments such as commit and push. Use them to block debug code, enforce commit message rules and add ticket IDs. See tested hook scripts, how to share them with core.hooksPath, how –no-verify bypasses them, and when to use a hook manager.
- Git hooks are executable scripts in a hooks folder. A non-zero exit code from a “pre” hook stops the action.
- Hooks in
.git/hooksare not shared. Commit them to a folder such as.githooksand rungit config core.hooksPath .githooks. - Our pre-commit hook blocked a commit containing
breakpoint(), and our commit-msg hook rejected “added total”. - Hooks run on the developer’s machine and
--no-verifyskips them, so repeat important checks in CI.
Code review keeps finding the same small problems: a forgotten debug breakpoint, a merge conflict marker, a commit message that says “fix” and nothing else. Each one wastes a reviewer’s time. Git hooks catch them on the developer’s machine before the commit even exists, in a fraction of a second.
We built and tested every hook below in a throwaway repository with Git 2.56, using Git Bash on Windows with a demo identity. The scripts are plain POSIX shell, so they also run on Linux and macOS.
What are git hooks?
A hook is a script that Git runs automatically when a certain event happens, such as just before a commit is recorded. Git passes it information through arguments and standard input. For “pre” hooks, the exit code decides what happens next: 0 lets the action continue, anything else aborts it. “Post” hooks run after the event and cannot stop it, so they suit notifications.
Where hooks live
Every new repository gets sample hooks. Our git init created 14 of them in .git/hooks, including pre-commit.sample, commit-msg.sample, pre-push.sample and prepare-commit-msg.sample. They do nothing until you remove the .sample suffix and make the file executable. Git ignores hooks without the executable bit.
The catch: .git is never committed, so hooks you put there exist only on your machine. Teammates do not get them, and neither does a fresh clone.
The most useful client-side hooks
| Hook | Runs | Can block? | Typical use |
|---|---|---|---|
pre-commit |
Before the commit message is asked for | Yes | Lint, format check, block debug code and secrets |
prepare-commit-msg |
Before the editor opens | Yes | Pre-fill the message, add a ticket ID |
commit-msg |
After the message is written | Yes | Enforce a message format |
post-commit |
After the commit | No | Notifications |
pre-push |
Before data is sent to a remote | Yes | Run fast tests, block pushes to main |
post-checkout / post-merge |
After switching branches or merging | No | Reinstall dependencies when lock files change |
Sharing hooks with core.hooksPath
Since Git 2.9, the core.hooksPath setting tells Git to look for hooks in any folder. Put your hooks in a committed folder and point Git at it:
mkdir .githooks
# ...add hook scripts...
chmod +x .githooks/*
git config core.hooksPath .githooks
git config --get core.hooksPath
# .githooks
The hooks are now versioned with the code and reviewed like any other change. Each developer still runs the git config line once after cloning, because Git will never enable hooks automatically for security reasons. A setup script or a make setup style command is a good place for it.
A pre-commit hook: block debug code and conflict markers
#!/bin/sh
# .githooks/pre-commit
# Block commits that contain leftover debug code or merge markers.
status=0
for f in $(git diff --cached --name-only --diff-filter=ACM -- '*.py'); do
if git diff --cached -U0 -- "$f" | grep -nE '^\+.*(breakpoint\(\)|import pdb)'; then
echo "pre-commit: debug code in $f" >&2
status=1
fi
done
if git diff --cached -U0 | grep -qE '^\+(<<<<<<<|>>>>>>>)'; then
echo "pre-commit: merge conflict markers found" >&2
status=1
fi
exit $status
Key details:
git diff --cachedchecks the staged changes, which is what will be committed, not the whole working folder.--diff-filter=ACMincludes added, copied and modified files and skips deleted ones.- Matching lines that start with
+means only newly added lines are checked, so old code does not block new commits. - Messages go to standard error, and the script exits with 1 when anything is found.
A commit-msg hook: enforce Conventional Commits
#!/bin/sh
# .githooks/commit-msg
# Enforce Conventional Commits: type(scope): subject
msg_file="$1"
first_line=$(head -n1 "$msg_file")
pattern='^(feat|fix|docs|test|refactor|chore)(\([a-z0-9-]+\))?: .{1,60}$'
if ! echo "$first_line" | grep -qE "$pattern"; then
echo "commit-msg: '$first_line' does not match type(scope): subject" >&2
exit 1
fi
Git passes the path of a temporary file holding the message as the first argument. The hook reads the first line and checks it against the pattern. Consistent messages make history readable and let tools generate changelogs and semantic version bumps automatically.
Watching the hooks run
We staged a Python file containing breakpoint() and tried to commit with a valid message:
git commit -m "feat(cart): add total"
8:+ breakpoint()
pre-commit: debug code in cart.py
exit=1
Blocked, with the offending line shown. We removed the breakpoint and tried a vague message:
git commit -m "added total"
commit-msg: 'added total' does not match type(scope): subject
exit=1
Blocked again, this time by the second hook. With both problems fixed, the commit went through:
git commit -m "feat(cart): add total helper"
exit=0
prepare-commit-msg: add the ticket ID automatically
Many teams put the ticket ID in every message. This hook reads it from a branch name such as feature/SQ-42-login:
#!/bin/sh
# .githooks/prepare-commit-msg
branch=$(git symbolic-ref --short HEAD 2>/dev/null)
ticket=$(echo "$branch" | grep -oE '[A-Z]+-[0-9]+')
if [ -n "$ticket" ] && [ "$2" = "message" ]; then
sed -i "1s/^/[$ticket] /" "$1"
fi
The second argument tells the hook where the message came from; message means it was given with -m. On our first try, the two hooks clashed:
commit-msg: '[SQ-42] feat(auth): add login stub' does not match type(scope): subject
prepare-commit-msg runs before commit-msg, so the validator saw the prefixed message and rejected it. We allowed an optional ticket prefix in the pattern:
pattern='^(\[[A-Z]+-[0-9]+\] )?(feat|fix|docs|test|refactor|chore)(\([a-z0-9-]+\))?: .{1,60}$'
Then the commit succeeded with the message [SQ-42] feat(auth): add login stub. We also checked the pattern on its own: it accepted feat: x and rejected added total, [sq-1] feat: x and Feat: y. Test hooks together, not just one at a time.
Bypassing hooks with –no-verify
git commit --no-verify -m "wip"
exit=0
We staged a file with a breakpoint and committed with --no-verify: both pre-commit and commit-msg were skipped and the commit was created, bad message and all. That escape hatch is useful in emergencies, but it means hooks are a convenience, not a guarantee. Anyone can skip them, and new clones do not have them until setup runs. Every rule that truly matters must also run in CI, as described in our GitHub Actions CI/CD guide.
Hook managers: pre-commit and Husky
Hand-written shell hooks are fine for a few checks. As rules grow, a manager helps:
- pre-commit (the Python framework): a
.pre-commit-config.yamlfile lists hooks from a large catalogue, such as formatters, linters and secret scanners, each pinned to a version.pre-commit installwires them up, andpre-commit run --all-filesruns them on demand or in CI. - Husky: popular in JavaScript projects. It stores hooks in a committed
.husky/folder and setscore.hooksPathfor you duringnpm install. - lint-staged: often paired with Husky to run tools only on staged files, which keeps hooks fast.
Managers solve the setup and versioning problems, and they run the same checks on every machine.
Server-side hooks
Git also has server-side hooks such as pre-receive and update, which run on the remote and can reject pushes. They cannot be bypassed by developers. Hosted platforms such as GitHub and GitLab usually do not let you install them; instead, they offer branch protection rules and required status checks, which achieve the same goal.
Notes for Windows users
- Git for Windows runs hooks through its bundled shell, so
#!/bin/shscripts work, as in our tests. - Save hook files with LF line endings. A CRLF in the first line breaks the shebang.
- Set the executable bit in the repository with
git update-index --chmod=+x .githooks/pre-commitso teammates on Linux and macOS get runnable files.
Tip: keep hooks fast. A pre-commit hook that takes 30 seconds teaches people to use --no-verify. Move slow test suites to pre-push or CI.
Best practices
- Commit hooks to the repository and set
core.hooksPathin your setup script. - Check only staged changes, and only newly added lines where possible.
- Print clear messages that say what failed and how to fix it.
- Keep pre-commit under a few seconds.
- Duplicate every important rule in CI, because hooks can be skipped.
- Scan for secrets such as API keys and private keys before they ever reach history.
Final thoughts
Git hooks are a cheap way to stop small mistakes at the source. A short pre-commit script blocks debug code and conflict markers, a commit-msg script keeps history clean, and prepare-commit-msg saves typing. Share them with core.hooksPath or a hook manager, keep them fast, test them together, and back them up in CI, because a hook only helps when it runs.
FAQ
What are git hooks used for?
They run scripts automatically at Git events such as commit or push, to lint code, block debug statements, enforce message formats or run quick tests.
How do I share git hooks with my team?
Commit the hook scripts to a folder such as .githooks and have each developer run git config core.hooksPath .githooks, or use a manager such as pre-commit or Husky.
How do I skip a git hook?
Add the no-verify option to git commit or git push. Because anyone can do this, important checks should also run in CI.
Why is my git hook not running?
The file may lack the executable bit, still have the sample suffix, use Windows line endings, or core.hooksPath may point to a different folder.
What is the difference between pre-commit and commit-msg hooks?
pre-commit runs before the message exists and checks the staged code. commit-msg runs after the message is written and checks the message text.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.