How to add Git's branch name to the commit message?

Here is my commit-msg script as an example:

#!/bin/sh
#
# Automatically adds branch name and branch description to every commit message.
#
NAME=$(git branch | grep '*' | sed 's/* //') 
DESCRIPTION=$(git config branch."$NAME".description)

echo "$NAME"': '$(cat "$1") > "$1"
if [ -n "$DESCRIPTION" ] 
then
   echo "" >> "$1"
   echo $DESCRIPTION >> "$1"
fi 

Creates following commit message:

[branch_name]: [original_message]

[branch_description]

I'm using issue number as branch_name, issue description is placed to the branch_description using git branch --edit-description [branch_name] command.

More about branch descriptions you can find on this Q&A.

The code example is stored in following Gist.


Use the prepare-commit-msg or commit-msg githook.

There are examples already in your PROJECT/.git/hooks/ directory.

As a security measure, you will have to manually enable such a hook on each repository you wish to use it. Though, you can commit the script and copy it on all clones into the .git/hooks/ directory.


A bit simpler script that adds the branch name to the commit message before you edit it. So if you want want to change or remove it you can.

Create this file .git/hooks/prepare-commit-msg:

#!/bin/bash

branchPath=$(git symbolic-ref -q HEAD) #Somthing like refs/heads/myBranchName
branchName=${branchPath##*/}      #Get text behind the last / of the branch path

firstLine=$(head -n1 $1)

if [ -z "$firstLine"  ] ;then #Check that this is not an amend by checking that the first line is empty
    sed -i "1s/^/$branchName: \n/" $1 #Insert branch name at the start of the commit message file
fi