Sub topic 8
Validating commit messages with commit-msg
This chapter assumes you can write a basic executable hook, as in the earlier pre-commit chapters. You should know that a hook is an executable file and that a non-zero exit status stops the Git action. You should also be comfortable with POSIX shell, grep and regular expressions.
The commit-msg hook checks the text of a commit message. A pre-commit hook sees the staged changes. This hook sees only the words you wrote about them. That makes it the right place to enforce a message convention such as type(scope): summary.
When commit-msg runs and what it receives
Git runs commit-msg late in the commit sequence, after the message exists but before the commit object is written. The order is:
pre-commitinspects the staged changes.prepare-commit-msgcan pre-fill the message.- The editor opens, unless you passed
-mor-F. commit-msgvalidates the finished message.- Git creates the commit.
Git passes exactly one argument to the hook: the path of a file that holds the proposed message. For a normal commit this is .git/COMMIT_EDITMSG. Your script must read that file. Nothing arrives on standard input.
The hook runs for git commit, including --amend, and also for commits that Git makes while completing a merge. git commit --no-verify (or -n) skips both pre-commit and commit-msg.
A minimal validator
This hook rejects any commit whose first line does not look like type(scope): summary.
#!/bin/sh
# .githooks/commit-msg
# $1 is the path to the file holding the proposed commit message.
if ! head -n 1 "$1" | grep -qE '^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+'; then
echo "commit-msg: the first line must look like 'type(scope): summary'." >&2
exit 1
fiInstall it the same way as any other hook. Make it executable and point core.hooksPath at the directory that holds it:
chmod +x .githooks/commit-msg
git config core.hooksPath .githooks
git commit --allow-empty -m "updated stuff"The commit is refused with the error message. Git then exits with a non-zero status, and no commit is created.
The script has no exit 0 at the end. That works because an if whose condition is true for the "good" case leaves the exit status at 0. Writing an explicit exit 0 is still clearer for readers.
Test the hook without committing
You do not need to make commits to test a message hook. Write a message to a temporary file and call the script directly:
printf 'updated stuff\n' > /tmp/msg
.githooks/commit-msg /tmp/msg
echo "exit status: $?"
printf 'fix(parser): handle empty input\n' > /tmp/msg
.githooks/commit-msg /tmp/msg
echo "exit status: $?"The first call prints the error and then exit status: 1. The second prints exit status: 0. This is the fastest way to iterate on a regular expression.
Problems with the minimal version
The five-line hook works for the common case. It breaks in several others.
Comment lines and leading blank lines
When Git opens an editor, the message file contains template text. Lines that start with # are comments, and Git removes them only after the hook has run. Git also strips leading blank lines later. If someone types their message below a blank line, head -n 1 sees an empty string and the check fails, even though Git would have accepted that message.
The fix is to ignore comment lines and blank lines before taking the first line.
Messages Git generates itself
Git writes some messages without your involvement, and they will not match your convention.
| Origin | Example first line | Usually allowed? |
|---|---|---|
| Merge | `Merge branch 'main' into feature` | Yes |
| Revert | `Revert "feat: add login"` | Yes |
| Autosquash | `fixup! fix: handle nulls` | Yes |
| Autosquash | `squash! feat: add cache` | Yes |
A hook that rejects these blocks git merge and git revert for no good reason. It also blocks git commit --fixup, which rebase then folds into another commit. Decide on an allowlist and match it before the format check.
Length and shape
A format check is a good place to add the limits most teams already agree on. A subject line of 72 characters or fewer shows well in git log --oneline and in code-hosting UIs. A blank line between subject and body keeps tools like git log --format=%s and git rebase -i reading the subject correctly.
A more complete hook
This version skips comments and blank lines, allows Git-generated subjects, checks the format, and enforces a length limit.
#!/bin/sh
# .githooks/commit-msg
# $1 is the path to the file holding the proposed commit message.
# First line that is not a comment and not blank.
subject=$(grep -v '^#' "$1" | grep -m 1 '[^[:space:]]')
# Let Git-generated messages through.
case "$subject" in
"Merge "*|"Revert "*|"fixup! "*|"squash! "*) exit 0 ;;
esac
if ! printf '%s\n' "$subject" | grep -qE '^(feat|fix|docs|chore|refactor|test)(\([a-z0-9._-]+\))?!?: .+'; then
echo "commit-msg: the first line must look like 'type(scope): summary'." >&2
echo "commit-msg: allowed types: feat, fix, docs, chore, refactor, test." >&2
echo "commit-msg: got: '$subject'" >&2
exit 1
fi
if [ "${#subject}" -gt 72 ]; then
echo "commit-msg: the first line is ${#subject} characters; the limit is 72." >&2
exit 1
fi
# If there is a second non-comment line, it must be blank.
second=$(grep -v '^#' "$1" | sed -n '2p')
if [ -n "$second" ]; then
echo "commit-msg: leave a blank line between the subject and the body." >&2
exit 1
fi
exit 0A few details are worth noting.
grep -m 1 '[^[:space:]]'prints the first line that contains any non-whitespace character. That skips blank lines.- The
!?before the colon allows the breaking-change marker, as infeat(api)!: drop v1. ${#subject}counts characters in most shells, but POSIX leaves multibyte behavior to the locale. For a strict byte limit, useprintf '%s' "$subject" | wc -c.- Error messages go to standard error with
>&2. Git shows both streams, but this keeps standard output clean for tools that wrap Git.
Rewriting a message from the hook
commit-msg may also modify the file. Git reads the message back after the hook finishes, so changes take effect. That lets a hook append a trailer, such as a ticket ID taken from the branch name.
#!/bin/sh
# .githooks/commit-msg (excerpt)
branch=$(git symbolic-ref --short HEAD 2>/dev/null)
ticket=$(printf '%s\n' "$branch" | grep -oE '[A-Z]+-[0-9]+' | head -n 1)
if [ -n "$ticket" ] && ! grep -q "$ticket" "$1"; then
tmp=$(mktemp)
{ cat "$1"; printf '\nRefs: %s\n' "$ticket"; } > "$tmp" && cat "$tmp" > "$1"
rm -f "$tmp"
fiThis writes through a temporary file because sed -i takes different arguments on GNU and BSD systems. Rewriting is usually better placed in prepare-commit-msg, where the developer sees the result before saving. Silent edits in commit-msg surprise people.
The hook is advisory
A client-side hook runs on the contributor's machine, under their configuration. It protects against honest mistakes, not against skipping. These common situations all let a bad message through:
git commit --no-verifyskips the hook.- A fresh clone has no
core.hooksPathsetting until the person runs the config command. - Edits made through a web UI, or by a bot, never run local hooks.
- A
git rebasethat picks commits without rewording does not re-validate their messages.
So the same rule needs to run in CI, over every commit in the pull request. Put the format check in one script and call it from both places. The script below takes the subject as an argument:
#!/bin/sh
# scripts/check-subject.sh
# Usage: check-subject.sh "subject line"
case "$1" in
"Merge "*|"Revert "*|"fixup! "*|"squash! "*) exit 0 ;;
esac
printf '%s\n' "$1" | grep -qE '^(feat|fix|docs|chore|refactor|test)(\([a-z0-9._-]+\))?!?: .+' || exit 1
[ "${#1}" -le 72 ] || exit 1The commit-msg hook then reduces to extracting the subject and calling this script:
#!/bin/sh
# .githooks/commit-msg
subject=$(grep -v '^#' "$1" | grep -m 1 '[^[:space:]]')
if ! scripts/check-subject.sh "$subject"; then
echo "commit-msg: bad subject: '$subject'" >&2
exit 1
fiThe CI job runs the same script over each commit in the branch:
#!/bin/sh
# scripts/ci-check-messages.sh
# Usage: ci-check-messages.sh origin/main
base="$1"
status=0
for sha in $(git rev-list "$base..HEAD"); do
subject=$(git log -1 --format=%s "$sha")
if ! scripts/check-subject.sh "$subject"; then
echo "bad subject in $sha: '$subject'" >&2
status=1
fi
done
exit $statusThe CI job needs enough history to resolve origin/main. Many CI systems clone shallowly by default, so configure a full fetch, or fetch the base branch explicitly. Otherwise git rev-list fails.
Common failures
| Symptom | Likely cause |
|---|---|
| The hook never runs | The file lacks the executable bit, the name has an extension such as `commit-msg.sh`, or `core.hooksPath` is not set in this clone. |
| `commit-msg: not found` or `bad interpreter` | The shebang points at a missing interpreter, or the file has Windows line endings (`\r\n`). |
| Valid messages are rejected in the editor flow | The check reads comment lines or a leading blank line as the subject. |
| `git merge` or `git revert` is blocked | The hook has no allowlist for Git-generated subjects. |
| Different results on macOS and Linux | `grep -E` handles `\d` or `\s` differently. Use POSIX classes such as `[[:digit:]]` and `[[:space:]]`. |
To see what Git is actually running, set GIT_TRACE=1 for one commit. The trace includes a line when Git starts the hook. If that line is missing, the problem is in the hook's path or permissions, not in your script's logic.
Exercise
A teammate commits with git commit -e and types a blank first line, then fix: handle nulls on line two. The minimal hook, which uses head -n 1, rejects it. Git itself would accept the message. Which two lines of the improved hook solve this, and what do they do?
Show answer
The line subject=$(grep -v '^#' "$1" | grep -m 1 '[^[:space:]]') removes comment lines and then takes the first line that contains a non-whitespace character. The check printf '%s\n' "$subject" | grep -qE ... then runs on that subject instead of on the literal first line, so the leading blank line no longer causes a rejection.
Exercise
Your team enforces the format with a commit-msg hook, and a developer still merges a commit titled "stuff". Name two ways that could happen, and the single control that closes both.
Show answer
They could have used git commit --no-verify, or their clone never had core.hooksPath configured, so the hook did not run. (Editing through a web UI also bypasses local hooks.) A CI job that runs the same check over every commit in the pull request closes all of these, because it does not depend on the developer's machine.