Bash Show git branch name in terminal prompt


Example

You can have functions in the PS1 variable, just make sure to single quote it or use escape for special chars:

gitPS1(){
    gitps1=$(git branch 2>/dev/null | grep '*')
    gitps1="${gitps1:+ (${gitps1/#\* /})}"
    echo "$gitps1"
}

PS1='\u@\h:\w$(gitPS1)$ '

It will give you a prompt like this:

user@Host:/path (master)$ 

Notes:

  • Make the changes in ~/.bashrc or /etc/bashrc or ~/.bash_profile or ~./profile file (depending on the OS) and save it.
  • Run source ~/.bashrc (distro specific) after saving the file.