commit-msg
- Git course
- Advanced
- Lesson 23/56
- 4 min
Learn message validation with the commit-msg hook.
What Is the commit-msg Hook?
The commit-msg hook runs before Git creates the commit and is used to validate the commit message. Git passes the path of the commit message file to this hook as an argument. The script can read this file and check whether the message follows specific rules.
#!/bin/sh
message_file="$1"
cat "$message_file"Validate the Commit Message Format
To enforce a specific commit message format, you can read the message file inside commit-msg. For example, you can require messages to start with feat:, fix:, or docs:. Return a nonzero exit code for an invalid message to block the commit.
#!/bin/sh
message=$(cat "$1")
case "$message" in
feat:*|fix:*|docs:*) exit 0 ;;
*) echo "Invalid message"; exit 1 ;;
esacPractice Validate a Commit Message Format
Write a Shell script for commit-msg. Read the message file from the first argument using cat. If the message starts with fix:, exit successfully; otherwise print Invalid commit message and use exit 1.
Starter code
# Mesajı oku
# Mesaj biçimini denetle
# Geçersizse hata döndürSample solution
message=$(cat "$1")
case "$message" in
fix:*) exit 0 ;;
*) echo "Geçersiz commit mesajı"; exit 1 ;;
esacExpected output
Geçersiz commit mesajı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What information does the commit-msg hook receive as an argument?
- The complete history of the current branch
- The path of the file containing the commit message Correct answer
- The remote repository URL
- The file list of the latest commit
Explanation: Git passes the temporary commit message file path as the first argument to the commit-msg hook. The script can read this file.
2 Read the Commit Message File
#!/bin/sh
message=$(cat "____")
#!/bin/sh
message=$(cat "$1")
Explanation: Git passes the message file path as the first argument to the commit-msg script. $1 represents this argument.
3 commit-msg Components
| Term | Meaning |
|---|---|
commit-msg |
Runs before message acceptance |
$1 |
Path of the message file |
cat |
Reads the file contents |
feat: |
New feature message |