How To Prefix Your Commit Message With a Ticket Number Automatically
Practical use-case for the prepare-commit-msg git hook
You don’t have to enter the ticket number manually for each commit!
Once the branch name contains that reference, you can set up the git hook to do it for you!
Git allows you to intercept the commit message using the
This hook is an executable file that Git calls right before the commit. It takes a single argument — the target filename that contains the commit message.
# GIT executes the prepare-commit-msg hook internally like:$ .git/hooks/prepare-commit-msg .git/COMMIT_EDITMSG
The task is to prepare a custom message based on the branch name and write it back to the
Here’s an example implementation in bash:
TICKET=[$(git rev-parse --abbrev-ref HEAD | grep -Eo '^(\w+/)?(\w+[-_])?[0-9]+' | grep -Eo '(\w+[-])?[0-9]+' | tr "[:lower:]" "[:upper:]")]
if [[ $TICKET == "" || "$MESSAGE" == "$TICKET"* ]];then
echo "$TICKET $MESSAGE" > $FILE
TICKET variable contains an extracted ticket number in brackets, like:
OK, now copy the script and place it in
your-repo/.git/hooks/pre-commit-msg and make it an executable file using the
chmod +x your-repo/.git/hooks/pre-commit-msg.
See it in action:
You may have noticed the condition:
if [[ $TICKET == "" || "$MESSAGE" == "$TICKET"* ]]
This is to guard against:
- an empty ticket number when the script can’t extract it
- a redundant ticket number when the message already contains one (e.g. when amending commits)
That’s all. Thank you for reading!