Custom Bash Prompt with Git Branch Name

bash prompt with git branch name in color

If you often use git from the terminal, you really should add the current branch to your prompt.

tl;dr

~/.bashrc

59
60
61
62
63
function parse_git {
   if branch=$(git symbolic-ref --short -q HEAD 2>/dev/null); then
       echo "[${branch}]" 
   fi
}

And add $(parse_git) to PS1 definition(s)

Backstory : bash prompt

The bash shell uses a special variable PS1 that is interpeted everytime bash shows the prompt.

To see what you PS1 is currently:

echo $PS1

For debian buster it is:

\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$

Concept: Bash prompt can run commands every time the prompt is shown

You can easily test changes to PS1 just by setting it. This example will set your prompt to the output from the date commmand. Example:

# prompt with just the date
PS1="$(date) "

Concept: Bash prompts can have colors

Colors are added to bash prompt for ANSI/VT100 with format codes.

echo -e "\033[01;31m\] turn on bright red"
echo -e "\033[00m turn on normal text"

Put it all together

Step 1: Add a command to show the current branch

For the bash prompt, it is easiest just to add a function to your ~/.bashrc file.

I will use git symbolic-ref “plumbing” command to get the current branch name.

59
60
61
62
63
function parse_git {
   if branch=$(git symbolic-ref --short -q HEAD 2>/dev/null); then 
       echo "[${branch}]" # I like to add square brackets
   fi
}

git symbolic-ref will avoid the “porcelain” command git branch which meant to be human readable.

Step 2: Add it to the PS1 command

I prefer to add $(parse_git) the system’s default PS1.

Open ~/.bashrc and change from this:

59
60
61
62
63
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

to this

59
60
61
62
63
64
65
66
67
68
69
function parse_git {
    if branch=$(git symbolic-ref --short -q HEAD 2>/dev/null); then
        echo "[${branch}]" 
    fi
}

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git)\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git)\$ '
fi

Produces this output:

new prompt bash prompt with git branch name in color

References