How To Prefix Your Commit Message With a Ticket Number Automatically

Practical use-case for the prepare-commit-msg git hook

Wiktor Malinowski
Dec 19, 2019 · 2 min read
Photo by Paulette Wooten on Unsplash

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 prepare-commit-msg hook.

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 .git/COMMIT_EDITMSG file.

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
exit 0;


The TICKET variable contains an extracted ticket number in brackets, like:

  • myproj-123-some-feature[MYPROJ-123]
  • feature/myproj-456-some-other-feature[MYPROJ-456]
  • bugifx/myproj-789[MYPROJ-789]
  • 123_some_feature [123]

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 command: chmod +x your-repo/.git/hooks/pre-commit-msg.

See it in action:

Ticket number auto-generated using inline commit.
Ticket number auto-generated in the text editor (commit without -m switch).

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!

Better Programming

Advice for programmers.

Wiktor Malinowski

Written by

Father, Husband, Software Engineer.

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

More from Better Programming

Why Do Incompetent Managers Get Promoted?


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade