Add JIRA Ticket Numbers to Git Commits using git hooks

X @urre


At work we use JIRA and usually use a consistent branch naming system where all branches and commits should include the ticket name.

For example branches looks like this:


and commits:

PROJ-1234 Fix tests

Setting up the Git Hook

Go to the git hooks directory inside your repo.

cd .git/hooks/

Create a file called prepare-commit-msg

touch .git/hooks/prepare-commit-msg

Make it executable.

chmod +x .git/hooks/prepare-commit-msg

Add the script

Open prepare-commit-msg in your editor and paste the following script:


# Create .git/hooks/prepare-commit-msg
# Run before using: chmod +x prepare-commit-msg

# Example: If the branch is called ex feature/dev/PROJ-1234-branch-name-example or
# feature/PROJ-6789/PROJ-1234-another-branch-name-example
# then the commit will be "PROJ-1234 Your commit message"

MESSAGE=$(cat "$FILE")
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)

# Extract the ticket number from the branch name
TICKET=$(echo "$BRANCH_NAME" | grep -Eo '(\w+/)?(\w+/)?(\w+[-_])?[0-9]+' | grep -Eo '(\w+[-])?[0-9]+' | tail -n 1 | tr "[:lower:]" "[:upper:]")

if [[ "$TICKET" == "[]" || "$MESSAGE" == "$TICKET"* ]]; then
    exit 0


This shell script extracts the JIRA ticket number from your branch name and appends it to your commit message.