Hooks are scripts that Git runs automatically at certain moments: before a commit is created, after a message is written, before a push. They let you catch problems at the earliest and cheapest point, on the developer's machine, seconds after they happen: a forgotten debug statement, a secret in a config file, a badly formatted commit message, failing tests. This lesson shows how hooks work, writes three useful ones, and explains how teams share and enforce them.
In simple words
- Git hook: a script Git runs automatically at certain moments, such as before a commit or a push.
- pre-commit: runs before a commit is made, for example to block secrets or run a linter.
- commit-msg: checks the commit message, for example that it follows Conventional Commits.
- pre-push: runs before pushing, for example to run tests.
How hooks work
Hooks live in .git/hooks/ inside each repository. Git ships sample files there (ending in .sample, so inactive). A hook is any executable file with the right name:
- If the hook exits 0, Git continues.
- If it exits non-zero, Git stops the action (for "pre-" hooks) and shows the hook's output.
| Hook | Runs | Typical use |
|---|---|---|
pre-commit | before the commit is created | lint, format check, secret scan, block debug code |
prepare-commit-msg | before the editor opens | add a ticket number from the branch name |
commit-msg | after the message is written (file path as $1) | enforce a message format |
post-commit | after the commit | notifications |
pre-push | before pushing (remote name and URL as arguments) | run tests |
post-checkout, post-merge | after switching or merging | reinstall dependencies |
server-side pre-receive, update | on the Git server | enforce policies for everyone |
git config --global user.name "Leela Kumar"mkdir hooks-labcd hooks-labgit initls .git/hooksInitialized empty Git repository in /home/lynuxpro/hooks-lab/.git/pre-commit.sampleA pre-commit hook: block debug code and secrets
This hook refuses commits whose staged files contain breakpoint(), a TODO-REMOVE marker or something that looks like an AWS access key:
#!/usr/bin/env bash# .git/hooks/pre-commitset -euo pipefailstatus=0for f in $(git diff --cached --name-only); do [[ -f $f ]] || continue if grep -nE 'breakpoint\(\)|TODO-REMOVE' "$f"; then echo "pre-commit: remove debug code from $f" >&2; status=1 fi if grep -nE 'AKIA[0-9A-Z]{16}' "$f"; then echo "pre-commit: possible AWS key in $f" >&2; status=1 fidoneexit $statusCreate a compact version in the practice terminal and make it executable:
printf '#!/usr/bin/env bash\nif grep -rnE "breakpoint\\(\\)|TODO-REMOVE" --include=*.py . ; then\n echo "pre-commit: remove debug code first" >&2\n exit 1\nfi\n' > .git/hooks/pre-commitchmod +x .git/hooks/pre-commitprintf 'def pay(x):\n breakpoint()\n return x\n' > pay.pygit add pay.pygit commit -m "Add pay"./pay.py:2: breakpoint()pre-commit: remove debug code firstThe commit was refused. Fix the file and commit again:
printf 'def pay(x):\n return x\n' > pay.pygit add pay.pygit commit -m "Add pay"[main (root-commit) 4d2e8a1] Add pay 1 file changed, 2 insertions(+) create mode 100644 pay.pyA commit-msg hook: enforce Conventional Commits
The commit-msg hook receives the path of the file holding the message as $1. This one requires messages like feat: …, fix(api): … or docs: …:
printf '#!/usr/bin/env bash\nmsg=$(head -n 1 "$1")\nif ! [[ $msg =~ ^(feat|fix|docs|chore|refactor|test|ci)(\\([a-z-]+\\))?:\\ .+ ]]; then\n echo "commit-msg: use Conventional Commits, e.g. \\"fix(api): handle timeouts\\"" >&2\n exit 1\nfi\n' > .git/hooks/commit-msgchmod +x .git/hooks/commit-msgprintf 'TAX_RATE = 0.18\n' > pricing.pygit add pricing.pygit commit -m "added pricing"git commit -m "feat(pricing): add GST rate"commit-msg: use Conventional Commits, e.g. "fix(api): handle timeouts"[main 7b3f9c2] feat(pricing): add GST rate 1 file changed, 1 insertion(+) create mode 100644 pricing.pyConsistent prefixes let tools generate changelogs and decide version numbers automatically (feat → minor, fix → patch, ! or BREAKING CHANGE → major).
A pre-push hook: run the tests
#!/usr/bin/env bash# .git/hooks/pre-pushecho "pre-push: running tests..."if ! python -m pytest -q; then echo "pre-push: tests failed, push aborted" >&2 exit 1fiKeep pre-push hooks fast (well under a minute); slow hooks get bypassed.
Skipping hooks
Any local hook can be skipped:
git commit --no-verify -m "Emergency fix"git push --no-verifyThat is sometimes legitimate, but it means local hooks are a convenience, not a guarantee. Anything that must always hold (tests pass, no secrets, approved reviews) has to be enforced on the server: CI pipelines, GitLab push rules (reject unsigned commits, files matching patterns, messages not matching a regex) and protected branches.
Sharing hooks with the team
.git/hooks is not part of the repository, so hooks are not cloned. Common solutions:
1. A committed hooks folder plus core.hooksPath:
mkdir -p .githookscp .git/hooks/pre-commit .githooks/git add .githooks && git commit -m "chore: share git hooks"git config core.hooksPath .githooks # each developer runs this once (or a setup script does)2. The pre-commit framework (pre-commit.com), the most popular tool. You list hooks in .pre-commit-config.yaml and it installs and runs them, in any language:
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: trailing-whitespace - id: check-yaml - id: check-merge-conflict - id: detect-private-key - repo: https://github.com/gitleaks/gitleaks rev: v8.21.2 hooks: - id: gitleaks - repo: https://github.com/antonbabenko/pre-commit-terraform rev: v1.96.2 hooks: - id: terraform_fmt - id: terraform_validatepip install pre-commitpre-commit install # sets up the git hookpre-commit run --all-files # run every hook on the whole repo (also great in CI)Running the same pre-commit run --all-files in the CI pipeline closes the --no-verify gap.
For JavaScript projects, husky and lint-staged play the same role.
Real-world scenario: the leaked key that never left the laptop
A platform team added gitleaks to their pre-commit configuration and to CI after a cloud key was pushed to a public repository and abused within an hour. A month later, a new engineer pasted a real access key into a test fixture. The pre-commit hook blocked the commit on their laptop with the exact file and line, before the key ever reached the server. The CI job that runs the same check was the backstop for anyone who skipped hooks.
Common mistakes
- Forgetting
chmod +x: a non-executable hook is silently ignored. - Slow hooks (full test suites on every commit), which people bypass with
--no-verify. - Relying on local hooks for security; enforce on the server too.
- Hooks that check the working tree instead of what is staged, letting unstaged fixes hide staged problems. Use
git diff --cached(or the pre-commit framework, which handles this). - Not sharing hooks, so only one person benefits.
Practice
- Write a
pre-commithook that blocks any staged file containingprint(and test it. - Write a
commit-msghook that requires a ticket number likeSHOP-123at the start of the message. - Bypass one hook with
--no-verifyand explain why the same check should also run in CI. - Move your hooks to a
.githooksfolder and pointcore.hooksPathat it.
Cheat sheet
.git/hooks/<name> hook location (must be executable)pre-commit | commit-msg ($1 = msg file) | pre-push ($1 remote, $2 url)exit 0 continue | non-zero stopgit diff --cached --name-only files being committedchmod +x .git/hooks/pre-commitgit commit --no-verify skip local hooksgit config core.hooksPath .githookspre-commit install | run --all-filesKey takeaways
- Hooks are executable scripts in
.git/hooksthat run at key moments; a non-zero exit stops the action. pre-commitcatches debug code, formatting and secrets;commit-msgenforces message conventions;pre-pushruns tests.- Local hooks can be skipped, so enforce important rules in CI and on the server as well.
- Share hooks with
core.hooksPathor the pre-commit framework.