Sub topic 4
Writing your first pre-commit hook
This chapter assumes you know the basic Git workflow (add, commit, push), can read and write short shell scripts, and understand the difference between the staging area (the index) and the working tree. You will write a working pre-commit hook, run it, and learn the mistakes that make hooks silently do nothing.
What a pre-commit hook does
The pre-commit hook is the first client-side hook Git runs during git commit. Git runs it before it asks for a commit message and before it creates a commit object. If the hook exits with a non-zero status, Git aborts the commit. If it exits with zero, the commit continues.
That gives you one job for a pre-commit hook: look at what is about to be committed and decide whether it is acceptable. Typical checks are whitespace errors, leftover conflict markers, formatting, linting, and accidentally staged secrets or debug statements.
The hook contract
Git finds a hook by name, so the file must be called exactly pre-commit, with no extension. It looks in the hooks directory, which is .git/hooks by default. The contract has three parts:
- The file must be executable. If the executable bit is missing, Git skips the hook and prints a hint (in recent versions) or nothing at all.
- The file must start with a shebang line such as
#!/bin/sh, unless it is a compiled binary. Without it, the kernel may fail to execute the file, or the shell may interpret it in a way you did not intend. - The exit status is the verdict.
0means pass. Any other value means fail.
The pre-commit hook receives no arguments. It runs with the repository's top-level directory as the working directory, so relative paths in your script resolve from the repository root.
Your first hook
Start with a check that needs no extra tools. git diff --cached --check inspects the staged changes and reports whitespace errors (trailing whitespace, a space before a tab in indentation) and leftover conflict markers. It exits non-zero when it finds a problem.
Create the hook in the default location:
#!/bin/sh
# .githooks/pre-commit
# Reject the commit if the staged changes contain whitespace errors or conflict markers.
if ! git diff --cached --check; then
echo "pre-commit: fix the problems above or commit with --no-verify." >&2
exit 1
fi
exit 0The script has three parts worth reading closely:
git diff --cached --checkcompares the index withHEAD.--cachedis the important flag. Without it, the command would inspect unstaged edits, which are not part of the commit.if !runs the command and tests for failure. Git prints the offending file and line numbers itself, so the script only adds a short instruction.- The message goes to standard error (
>&2). Git shows both streams to the user, but stderr is the convention for diagnostics.
The path in the comment, .githooks/pre-commit, matches the shared setup used later in this chapter. For a quick local test you can instead save the file as .git/hooks/pre-commit.
Install and test it
mkdir -p .githooks
chmod +x .githooks/pre-commit
git config core.hooksPath .githooks
git add .githooks
git commit -m "Add shared pre-commit hook"This does four things. It creates a tracked directory for hooks, sets the executable bit, tells Git to look for hooks there, and commits the hook itself. The core.hooksPath setting is covered fully in a later chapter on sharing hooks. It matters here because .git/hooks is never versioned, so a hook placed there exists only on your machine.
Now trigger a failure on purpose:
printf 'hello \n' > demo.txt
git add demo.txt
git commit -m "Add demo file"The file contains trailing spaces, so the hook should fail. The output looks similar to this:
demo.txt:1: trailing whitespace.
+hello
pre-commit: fix the problems above or commit with --no-verify.Run git log -1 afterwards. The latest commit is still the hook commit, which confirms that no new commit was created. Fix the file, stage it again, and the commit succeeds:
printf 'hello\n' > demo.txt
git add demo.txt
git commit -m "Add demo file"Exit status in detail
The exit status is the only thing Git reads from a pre-commit hook. Output text does not matter. This has a few consequences:
- A script that prints "ERROR" but ends with
exit 0allows the commit. - A script with no explicit
exitreturns the status of its last command. If that last command is an unrelatedecho, the hook passes even though an earlier check failed. - A pipeline returns the status of its last command in POSIX
sh. Incmd1 | cmd2, a failure incmd1is hidden unless you handle it.
Keep the status explicit. The pattern from the first hook, where a failed check leads to exit 1 and the script ends with exit 0, is hard to get wrong.
To collect several failures before exiting, record them in a variable and exit once at the end. This lets the developer see every problem in a single run:
#!/bin/sh
status=0
if ! git diff --cached --check; then
status=1
fi
if git diff --cached --name-only | grep -q '\.env$'; then
echo "pre-commit: refusing to commit a .env file." >&2
status=1
fi
exit $statusHere grep -q produces no output and exits 0 when it finds a match. The if therefore treats a match as the failure case.
Checking staged content with a tool
Real checks often call a linter. The next hook runs shellcheck on every staged shell script:
#!/bin/sh
# .githooks/pre-commit
# Run shellcheck on the staged version of each added, copied or modified .sh file.
status=0
for f in $(git diff --cached --name-only --diff-filter=ACM -- '*.sh'); do
git show ":$f" | shellcheck - || status=1
done
exit $statusEach piece does specific work:
| Part | Purpose | Column | Column |
|---|---|---|---|
| `--name-only` | Lists paths only, not the diff text. | ||
| `--diff-filter=ACM` | Keeps Added, Copied and Modified files. Deleted files are skipped, because there is nothing to check. | ||
| `-- '*.sh'` | Limits the list to paths matching the pattern. The quotes stop the shell from expanding the pattern against the working directory. | ||
| `git show ":$f"` | Prints the staged version of the file. The leading colon means "from the index". | ||
| `shellcheck -` | Reads the script from standard input. | ||
| `\ | \ | status=1` | Records a failure but lets the loop continue. |
The use of git show ":$f" is deliberate. If you ran shellcheck "$f" instead, it would read the working tree copy. Suppose you stage a broken script, then fix it in your editor without staging the fix. The working tree copy is clean, the hook passes, and the broken version is committed. Reading from the index checks what will actually be committed. A later chapter covers this distinction in more depth.
Pitfalls with auto-fixing hooks
It is tempting to have the hook reformat files and then run git add on them. This is risky. If the developer staged only part of a file with git add -p, your git add stages the entire file, including edits they chose to leave out. Prefer to report problems and fail, and let the developer fix them. Hook managers that do auto-fix usually stash unstaged changes around the run to avoid this problem.
When the hook does not run
A hook that never fires looks the same as a hook that passes. Check these causes in order:
- Wrong name.
pre-commit.shorprecommitis ignored. Git also ignores files ending in.sample. - Not executable. Run
ls -l .githooks/pre-commitand look forxin the permissions. Fix withchmod +x. - Wrong location. If
core.hooksPathis set, Git ignores.git/hookscompletely. Rungit config core.hooksPathto see which directory is in use. - Bypassed.
git commit --no-verify(or-n) skipspre-commitandcommit-msg. - Bad shebang. An interpreter path that does not exist, or Windows line endings (
\r\n) in the shebang line, produces errors such asbad interpreterorno such file or directory.
A fast way to test a hook without making a commit is to run it directly:
.githooks/pre-commit; echo "exit status: $?"Because the hook reads the index and not the commit process, it behaves the same when you call it by hand.
Limits of a local hook
A pre-commit hook is a convenience for the person committing. It is not enforcement. Any developer can skip it with --no-verify, a fresh clone has no hooks until core.hooksPath is set, and commits made through a web interface never run it. Treat the hook as fast feedback, and repeat the important checks in continuous integration, which a later chapter covers.
Exercises
Exercise
A hook prints "Lint failed!" when a check fails but the script has no exit statement, and the last line is echo "done". Commits still go through. Why, and what is the fix?
Show answer
Without an explicit exit, the script returns the status of its last command. echo "done" succeeds, so the status is 0 and Git continues with the commit. The text printed earlier has no effect. Fix it by exiting with a non-zero status on failure (for example exit 1 inside the failure branch), or by tracking a status variable and ending with exit $status.
Exercise
You stage deploy.sh, which has a syntax problem, then fix the problem in your editor without running git add again. Your hook runs shellcheck deploy.sh. Does the hook block the commit, and does the commit contain the fixed or the broken script?
Show answer
The hook does not block the commit, because shellcheck deploy.sh reads the working tree copy, which is fixed. The commit contains the staged copy, which is still broken. To check what will be committed, read the staged version with git show ":deploy.sh" | shellcheck -.
Exercise
You created .githooks/pre-commit and ran git config core.hooksPath .githooks, but a commit with trailing whitespace succeeds. List two things to check.
Show answer
Check that the file is executable (ls -l .githooks/pre-commit, fix with chmod +x), and that the name is exactly pre-commit with no extension. Other valid answers: confirm git config core.hooksPath prints .githooks in this repository, confirm the commit was not made with --no-verify, and confirm the shebang line is valid and has no Windows line endings.