Skip to main content
Chapter 55 of 61 · 1 sections · Page 179

Git: Branch Name in Bash Prompt

Customize PS1 in bash to display the active Git branch dynamically in your terminal prompt.

Original chapter reference: Chapter 55: Git Branch Name on Bash Ubuntu. The command options and documentation recipes below are fully transcribed from Git Notes for Professionals.

This documentation deals with the branch name of the git on the bash terminal. We developers need to find the git branch name very frequently. We can add the branch name along with the path to the current directory.

Section 55.1: Branch Name in terminal

What is PS1

PS1 denotes Prompt String 1. It is the one of the prompt available in Linux/UNIX shell. When you open your terminal, it will display the content defined in PS1 variable in your bash prompt. In order to add branch name to bash prompt we have to edit the PS1 variable (set value of PS1 in ~/.bash_profile).

Display git branch name

Add following lines to your ~/.bash_profile

Source example · PDF page 179
git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(git_branch)\[\033[00m\] $ "

This git_branch function will find the branch name we are on. Once we are done with this changes we can navigate to the git repo on the terminal and will be able to see the branch name.

Buy me a coffee
Daily Practice
0/0