---
title: "git hook - prefix your commit message with your JIRA ticket"
description: "In this short blog post I'll show you how you can automatically prefix your commit messages with the JIRA ticket derived from your branch name."
updated: 2021-09-23
tags: ["hook", "jira", "git", "shorts"]
canonical: "https://steven-giesel.com/blogPost/b104e1f0-f5c5-4be7-9ad4-9eb923bb6603/git-hook-prefix-your-commit-message-with-your-jira-ticket"
---

# git hook - prefix your commit message with your JIRA ticket

If you follow [gitflow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow#:~:text=Gitflow%20is%20a%20legacy%20Git,software%20development%20and%20DevOps%20practices.) or [github-flow](https://guides.github.com/introduction/flow/) you will have branch names like this: `feature/JIRA-1234-My-Feature` or `bugfix/ABC-121-Issue`. And most of the times your commit messages will start the same: `JIRA-1234 Created the button` or `ABC-121 Reverted Refactoring`.

## The Hook

```bash
#!/bin/sh
if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(main develop)
fi

BRANCH_NAME=$(git symbolic-ref --short HEAD)
TICKET_NAME=$(echo $BRANCH_NAME | grep -Poi '\w*/\K([0-9]+)')
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
ALREADY_IN_MSG=$(grep -ci "$TICKET_NAME" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ "$BRANCH_EXCLUDED" -eq 1 ]] && ! [[ "$ALREADY_IN_MSG" -eq 1 ]]; then
  sed -i.bak -e "1s/^/AB#${TICKET_NAME^^} /" "$1"
fi
```

Now if you are on your `feature/JIRA-1234-Something` branch and created a commit message without your ticket it will automatically prefix your ticket, so:
```
git commit -m "Test"
```  
Will result in
```
JIRA-1234 Test
``` 
If you still prefix your ticket with this, don't worry, this will not prefix your message a second time. And the git hook works in all GUI's (Visual Studio, Rider, Source-Tree) or via the CLI.

## How to install?
To use it you have to go into the `.git` folder of your repository. There you find a `hooks` folder with a lot of sample files.
The hook we have written is called `prepare-commit-msg`. So create a new file called `prepare-commit-msg`. **There is no extension** and copy the content et voilà: You save about 0.52 seconds per commit message ;)