Git hooks
Overview
Hooks are scripts that Git runs automatically at specific points: before a commit is created, after a merge, before a push, and so on. They let you catch mistakes at the earliest and cheapest moment — a lint error caught before committing never reaches review, let alone CI.
How hooks work
A hook is an executable file with a specific name in the hooks folder — by default .git/hooks/. Every new repository contains *.sample examples there; remove .sample and make one executable to activate it.
- Hooks can be written in any language — shell, Python, Node — as long as the file is executable and has a shebang line (
#!/bin/sh). - Git passes information as arguments and environment variables (for example,
commit-msgreceives the path of the message file). - For “pre” hooks, exiting with a non-zero code aborts the operation. Anything the hook prints is shown to the user, so explain what went wrong.
The most useful client-side hooks
| Hook | Runs | Typical use |
|---|---|---|
pre-commit |
before the commit is created | lint/format staged files, block debug code or secrets |
prepare-commit-msg |
before the editor opens | pre-fill the message (e.g. the issue number from the branch name) |
commit-msg |
after the message is written | enforce a format such as Conventional Commits |
post-commit |
after the commit | notifications |
pre-push |
before pushing | run the test suite, block pushes to main |
post-checkout, post-merge |
after switching or merging | reinstall dependencies when the lockfile changed |
pre-commit: check what’s staged
#!/bin/sh
if git diff --cached -U0 | grep -q '^+.*console\.log'; then
echo "pre-commit: remove console.log before committing" >&2
exit 1
fiThe key detail: check the staged changes (git diff --cached), not the working directory — that’s what will actually be committed.
Watch out for false positives: this exact hook would block committing itself, because its error message contains console.log. Real hooks usually limit checks to source folders or file types (for example, only staged *.js files under src/).
commit-msg: enforce a format
#!/bin/sh
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9-]+\))?!?: .+'
head -1 "$1" | grep -Eq "$pattern" || {
echo "commit-msg: use 'type(scope): subject'" >&2
exit 1
}Sharing hooks with the team
The .git folder isn’t committed, so hooks in .git/hooks stay on your machine. Two ways to share them:
core.hooksPath
Commit the hooks to a normal folder and point Git at it:
mkdir .githooks
# …add executable hooks…
git config core.hooksPath .githooksEach developer runs the git config line once (often from a setup script or npm install). On Windows, Git Bash runs shell hooks fine; remember to commit them with the executable bit (git update-index --chmod=+x .githooks/pre-commit if your OS doesn’t track it).
Hook managers
Most teams use a tool that installs and runs hooks from a config file:
- Husky and lint-staged — popular in JavaScript projects; lint-staged runs linters on staged files only.
- pre-commit (pre-commit.com) — language-agnostic, with a large library of ready-made hooks, including secret detection.
- lefthook — fast, language-agnostic, parallel hooks.
They handle installation, cross-platform quirks and running checks only on the files that changed.
Keep hooks fast
A hook that takes a minute on every commit will be bypassed. Lint and format only staged files in pre-commit; save the full test suite for pre-push or CI.
The limits of local hooks
Local hooks are a convenience, not a guarantee:
- they aren’t installed until each developer sets them up,
- anyone can skip them:
git commit --no-verify,git push --no-verify, - they don’t run for commits made on GitHub’s website.
So enforce anything that must hold on the server: CI checks that run the same linters and tests, and branch rules that require them (Protecting branches). Hooks give fast feedback on your machine; CI makes it binding.
(Git servers also support server-side hooks such as pre-receive and update, which can reject pushes. GitHub.com doesn’t allow custom server hooks — its equivalents are rulesets, required checks and push protection.)
Hooks in Git config (Git 2.54+)
Newer Git versions can also define hooks in configuration instead of as files in a folder, and run several hooks for the same event:
# ~/.gitconfig — runs before every commit, in every repository
[hook "linter"]
event = pre-commit
command = ~/bin/linter
[hook "no-leaks"]
event = pre-commit
command = ~/bin/leak-detectorgit hook list pre-commit shows which hooks will run and where they’re configured. Since Git 2.55 they can also run in parallel. This is handy for personal checks you want everywhere; for team hooks, the folder-based approach in this lesson works with every Git version and remains the most common.
Use hooks to help, CI to enforce. A good pre-commit hook saves you from embarrassing commits in a second; a required CI check protects
mainno matter what.
Guard your commits with hooks
Create a shared hooks folder .githooks/ in the repository and point Git at it with core.hooksPath. Write two hooks: a pre-commit hook that refuses to commit any staged file containing the text console.log, and a commit-msg hook that rejects messages not in Conventional Commits form (type: subject or type(scope): subject). Prove each one works: a commit with console.log and a commit with message “stuff” must both fail, and a clean commit with feat: add cart must succeed. Then show how --no-verify skips them — and why CI must still check.
mkdir hooks && cd hooks && git init -qb main
echo "# App" > README.md && git add . && git commit -qm "chore: start app"
# 1. Shared hooks folder + core.hooksPath
# 2. pre-commit: block staged console.log
# 3. commit-msg: require Conventional Commits
# 4. Test: console.log is refused
# 5. Test: bad message is refused, good message accepted
# 6. --no-verify skips local hooksmkdir hooks && cd hooks && git init -qb main
echo "# App" > README.md && git add . && git commit -qm "chore: start app"
# 1. Shared hooks folder (switched on with core.hooksPath after committing, below)
mkdir .githooks
# 2. pre-commit: block staged console.log
cat > .githooks/pre-commit <<'EOF'
#!/bin/sh
# Look only at what is staged, not at the working directory.
if git diff --cached -U0 | grep -q '^+.*console\.log'; then
echo "pre-commit: remove console.log before committing" >&2
exit 1
fi
EOF
# 3. commit-msg: require Conventional Commits
cat > .githooks/commit-msg <<'EOF'
#!/bin/sh
# $1 is the file containing the commit message.
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9-]+\))?!?: .+'
if ! head -1 "$1" | grep -Eq "$pattern"; then
echo "commit-msg: use 'type(scope): subject', e.g. 'fix(cart): include quantity'" >&2
exit 1
fi
EOF
chmod +x .githooks/pre-commit .githooks/commit-msg
git add .githooks && git commit -qm "chore: add git hooks"
# Switch the hooks on only now: the pre-commit hook's own error message
# mentions console.log, so it would have blocked the commit that adds it!
git config core.hooksPath .githooks
# 4. Test: console.log is refused
echo "console.log('debug')" > app.js && git add app.js
git commit -qm "feat: add app" && echo "UNEXPECTED" || echo "blocked by pre-commit ✓"
# 5. Test: bad message is refused, good message accepted
echo "export const cart = []" > app.js && git add app.js
git commit -qm "stuff" && echo "UNEXPECTED" || echo "blocked by commit-msg ✓"
git commit -qm "feat: add cart" && echo "accepted ✓"
# 6. --no-verify skips local hooks — which is why CI must enforce the important rules too
echo "console.log('oops')" >> app.js && git add app.js
git commit -q --no-verify -m "whatever" && echo "hooks skipped with --no-verify"Summary
- Hooks are executable scripts Git runs at certain moments; a non-zero exit stops the operation.
- Common client hooks: pre-commit (lint staged files), commit-msg (check the message), pre-push (run tests).
- Hooks in
.git/hooksaren’t shared — commit them to a folder and setcore.hooksPath, or use a hook manager. - Check only staged content in pre-commit, and keep hooks fast so people don’t bypass them.
- Local hooks can be skipped with
--no-verify; enforce what really matters in CI and branch rules.