Hook Types
Hook Types: Pre-Commit, Commit-Msg, Pre-Push
After this page you can name the client hooks this book uses and where they live on Linux.
A hook is a program Git runs
Executable files in .git/hooks/. Git looks at the filename. If pre-commit exists and is executable (chmod +x), Git runs it before it writes a commit object. Exit status 0 continues. Non-zero aborts.
git commit
│
▼
pre-commit exit ≠ 0 ──► abort, no object
│ 0
▼
commit-msg exit ≠ 0 ──► abort, no object
│ 0
▼
commit object written, main slides forward
git push
│
▼
pre-push exit ≠ 0 ──► abort, remote unchanged
│ 0
▼
objects uploaded
Sample files are *.sample and are not run. Copy and chmod:
cd ~/desk/desk-api
ls .git/hooks
install -m 0755 .git/hooks/pre-commit.sample .git/hooks/pre-commit
# then edit; or write your owninstall -m 0755 is the Linux way to copy and set the executable bit in one step.
Client hooks you will write
| Hook | When | Typical job |
|---|---|---|
pre-commit |
After you type git commit, before the object exists |
Lint, block secrets, git diff --check |
commit-msg |
After you save the message | Conventional Commits pattern |
pre-push |
After you type git push, before objects upload |
Tests, block WIP branches |
There are more (prepare-commit-msg, post-commit, post-checkout). Start with these three.
Server hooks (later)
A forge runs pre-receive / update / post-receive on the server when you push. Chapter 23 names them; chapter 31 uses them for policy. Your laptop hooks do not run on the server. A teammate can skip pre-commit with git commit --no-verify. Server hooks are the ones that actually enforce.
Environment
Hooks run with a POSIX shell on Linux unless the shebang says otherwise. Always start with:
#!/usr/bin/env bash
set -euo pipefailGit sets GIT_DIR and runs with the working tree as cwd for client hooks (with nuances for worktrees, chapter 14). Print to stderr so you do not pollute commit output:
echo "pre-commit: running" >&2