Skip to content
$ lynuxpro
← Git

LESSON 17 OF 21 · ADVANCED · 18 MIN

Git hooks

HOW IT WORKSHooks run at key moments

git commitpre-commitlint, secrets scancommit-msgcheck message formatCommit createdpre-pushrun testsServer-side checksCI, protected branches
1/5

Hooks are scripts in .git/hooks that Git runs automatically. A non-zero exit stops the action.

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.
HookRunsTypical use
pre-commitbefore the commit is createdlint, format check, secret scan, block debug code
prepare-commit-msgbefore the editor opensadd a ticket number from the branch name
commit-msgafter the message is written (file path as $1)enforce a message format
post-commitafter the commitnotifications
pre-pushbefore pushing (remote name and URL as arguments)run tests
post-checkout, post-mergeafter switching or mergingreinstall dependencies
server-side pre-receive, updateon the Git serverenforce policies for everyone
git config --global user.name "Leela Kumar"mkdir hooks-labcd hooks-labgit initls .git/hooks
SHELLbashutf-8 · 5L
Initialized empty Git repository in /home/lynuxpro/hooks-lab/.git/pre-commit.sample
OUTPUTterminalutf-8 · 2L

A 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 $status
SHELLbashutf-8 · 14L

Create 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"
SHELLbashutf-8 · 5L
./pay.py:2:    breakpoint()pre-commit: remove debug code first
OUTPUTterminalutf-8 · 2L

The 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"
SHELLbashutf-8 · 3L
[main (root-commit) 4d2e8a1] Add pay 1 file changed, 2 insertions(+) create mode 100644 pay.py
OUTPUTterminalutf-8 · 3L

A 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"
SHELLbashutf-8 · 6L
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.py
OUTPUTterminalutf-8 · 4L

Consistent 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 1fi
SHELLbashutf-8 · 7L

Keep 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-verify
SHELLbashutf-8 · 2L

That 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)
SHELLbashutf-8 · 4L

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_validate
OUTPUTterminalutf-8 · 17L
pip 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)
SHELLbashutf-8 · 3L

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

  1. Write a pre-commit hook that blocks any staged file containing print( and test it.
  2. Write a commit-msg hook that requires a ticket number like SHOP-123 at the start of the message.
  3. Bypass one hook with --no-verify and explain why the same check should also run in CI.
  4. Move your hooks to a .githooks folder and point core.hooksPath at 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-files
OUTPUTterminalutf-8 · 8L

Key takeaways

  • Hooks are executable scripts in .git/hooks that run at key moments; a non-zero exit stops the action.
  • pre-commit catches debug code, formatting and secrets; commit-msg enforces message conventions; pre-push runs tests.
  • Local hooks can be skipped, so enforce important rules in CI and on the server as well.
  • Share hooks with core.hooksPath or the pre-commit framework.