Sub topic 4
Writing your first pre-commit hook
This chapter assumes you know the basic Git workflow (add, commit, push), the difference between the staging area and the working tree, and enough shell to read a short sh script. By the end you will have a working pre-commit hook that blocks bad commits.
What pre-commit does
Git runs the pre-commit hook after you run git commit and before it asks for a commit message. The hook is an ordinary executable file. If it exits with status 0, the commit continues. If it exits with any other status, Git aborts the commit and nothing is recorded.
Because the hook runs before the message editor opens, a failed check costs you no typing.
A minimal hook
Git has a built-in check that fits this job. git diff --cached --check looks at the staged changes and reports whitespace errors, such as trailing spaces, and leftover conflict markers. It exits non-zero when it finds any.
#!/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 0Three details matter here:
- The first line,
#!/bin/sh, tells the operating system which interpreter runs the file. Without it, the hook may fail with an "exec format error". - Messages go to standard error (
>&2) so they show up even when Git captures standard output. - The explicit
exit 1is what blocks the commit. Printing a warning alone does nothing.
Installing the hook
Git looks for hooks in .git/hooks by default, and each hook must have the exact name of its event, with no file extension. Save the script as .git/hooks/pre-commit, then make it executable:
chmod +x .git/hooks/pre-commitGit silently ignores a hook that is not executable. This is the most common reason a new hook "does nothing". Git may print a hint about the ignored hook, but only in newer versions.
Trying it out
Create a file with a trailing space, stage it, and commit:
printf 'hello \n' > notes.txt
git add notes.txt
git commit -m "Add notes"The hook prints something like notes.txt:1: trailing whitespace. and the commit is refused. Remove the trailing space, run git add notes.txt again, and the commit goes through.
Checking a tool on staged files
Real hooks usually run a linter. The script below runs ShellCheck on every added, copied or modified .sh file.
#!/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 $statusThe script follows a pattern worth copying:
--name-onlylists the paths of staged files.--diff-filter=ACMkeeps added, copied and modified files, so deleted files are skipped.- The
statusvariable lets the loop check every file before failing. You see all problems in one run instead of one per attempt. git show ":$f"reads the staged version of the file, not the copy in your working tree. If you staged part of a file withgit add -p, the hook checks what will actually be committed. The next chapter covers this in detail.
Common errors
| Symptom | Likely cause |
|---|---|
| Hook never runs | File is not executable, or its name has an extension such as `pre-commit.sh` |
| `exec format error` | Missing or wrong shebang line |
| Hook passes but bad code is committed | The hook checked the working tree instead of the staged content |
| Commit blocked with no message | The hook exited non-zero without printing anything |
You can bypass a hook for one commit with git commit --no-verify. This is useful in an emergency, but it also means hooks cannot be your only line of defence.
Exercise
A teammate saves a script as .git/hooks/pre-commit, adds exit 1 on the first non-comment line, and runs git commit. The commit succeeds anyway. Name two causes you would check first.
Show answer
First, check whether the file is executable (ls -l .git/hooks/pre-commit, fix with chmod +x), because Git ignores non-executable hooks. Second, check the filename and the shebang line: the name must be exactly pre-commit with no extension, and the first line must name a valid interpreter such as #!/bin/sh. Also confirm the commit was not run with --no-verify.
Exercise
Why does the ShellCheck hook use git show ":$f" instead of passing $f straight to shellcheck?
Show answer
Passing $f makes ShellCheck read the working tree copy, which may contain unstaged edits that differ from what will be committed. git show ":$f" prints the version in the index, so the check covers exactly the content that goes into the commit.