Git commit-msg Hook to Check Message Format

The commit-msg hook runs after you write the commit message. This one allows only messages like feat: add login or fix: cart total, which keeps the history easy to read.

#!/bin/sh
# Allow only messages that start with feat:, fix:, docs: or chore:

MSG_FILE="$1"
FIRST_LINE=$(head -n 1 "$MSG_FILE")

if ! echo "$FIRST_LINE" | grep -E '^(feat|fix|docs|chore): .+' > /dev/null; then
  echo "Bad commit message: $FIRST_LINE"
  echo "Use: feat: ..., fix: ..., docs: ... or chore: ..."
  exit 1
fi
Terminal output

$ chmod +x .git/hooks/commit-msg
$ git commit -m "added file"
Bad commit message: added file
Use: feat: …, fix: …, docs: … or chore: …
$ git commit -m "feat: add first file"
[main (root-commit) 7a05184] feat: add first file
1 file changed, 1 insertion(+)
create mode 100644 a.txt
$ git log –oneline
7a05184 (HEAD -> main) feat: add first file

How it works

  • Git gives the hook the path of a temporary file with the message as the first argument ($1).
  • The script reads the first line and checks it with a regular expression.
  • When the script exits with 1, Git cancels the commit and the message is not saved.
Note: Hooks stay only in your own .git/hooks folder. For a team, keep the scripts in the project and use git config core.hooksPath .githooks. See Git Hooks.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.