How to Use Git commit-msg Hook for Commit Message Validation
Use the
commit-msg hook by creating an executable script in the .git/hooks/ directory named commit-msg. This script runs automatically after you type a commit message and can validate or modify the message before the commit is finalized.Syntax
The commit-msg hook is a script placed in the .git/hooks/ folder of your repository. It receives one argument: the path to a temporary file containing the commit message. The script should exit with 0 to accept the commit or a non-zero code to reject it.
$1: Path to the commit message file- Exit
0: Commit message is valid - Exit non-zero: Commit is aborted
sh
#!/bin/sh # $1 is the commit message file commit_msg_file="$1" # Example: check if commit message is empty if [ ! -s "$commit_msg_file" ]; then echo "Error: Commit message is empty." >&2 exit 1 fi exit 0
Example
This example script checks that the commit message starts with a capital letter and is at least 10 characters long. If the message does not meet these rules, the commit is rejected with an error message.
sh
#!/bin/sh commit_msg_file="$1" commit_msg=$(head -n1 "$commit_msg_file") # Check if first character is uppercase first_char=$(echo "$commit_msg" | cut -c1) if ! echo "$first_char" | grep -q '^[A-Z]'; then echo "Error: Commit message must start with a capital letter." >&2 exit 1 fi # Check minimum length msg_length=$(echo -n "$commit_msg" | wc -c) if [ "$msg_length" -lt 10 ]; then echo "Error: Commit message must be at least 10 characters." >&2 exit 1 fi exit 0
Output
Error: Commit message must start with a capital letter.
# or
Error: Commit message must be at least 10 characters.
Common Pitfalls
- Not making the
commit-msgscript executable withchmod +x .git/hooks/commit-msg. - Using incorrect script syntax or not handling the commit message file argument properly.
- Forgetting to exit with a non-zero code to reject bad commit messages.
- Modifying the commit message file incorrectly, which can corrupt the commit.
sh
# Wrong: script not executable # No output, commit always succeeds # Right: make script executable chmod +x .git/hooks/commit-msg
Quick Reference
Remember these key points when using the commit-msg hook:
- Place your script in
.git/hooks/commit-msg - Make it executable with
chmod +x - Use the first argument as the commit message file path
- Exit
0to accept, non-zero to reject - Print error messages to
stderrto inform the user
Key Takeaways
Create an executable script named commit-msg in .git/hooks to validate commit messages.
The script receives the commit message file path as its first argument.
Exit with 0 to accept the commit or non-zero to reject it with an error.
Always test your hook script to avoid blocking commits unintentionally.
Use clear error messages to guide users on commit message requirements.