Show Current Git Branch in Bash Prompt

Current Git Branch In Bash Prompt

If you’ve added autocomplete functionality for Git using the git-completion.bash script, then you’re in for a treat. You can use a function of the script to show the current Git branch in your Bash prompt. All you have to do is a little snippet to your $PS1 environment variable like so:

PS1='\! \u:\W$(__git_ps1 "(%s)")\$ '

With color, mine looks like this:

export PS1='\[\033[1;34m\]\!\[\033[0m\] \[\033[1;35m\]\u\[\033[0m\]:\[\033[1;35m\]\W\[\033[0m\] \[\033[1;92m\]$(__git_ps1 "(%s)")\[\033[0m\]\$ '

To test the functionality, navigate to a git repository in your shell. Wahla! Magic.

**UPDATE: 2013-01-25**

Dirty/Clean Status in Prompt

If you want to see the dirty/clean status of your current branch in the command prompt next to the branch name, simply add this line to your bash_profile/bashrc if you’re already using __git_ps1:

export GIT_PS1_SHOWDIRTYSTATE=1

Explanation from git-completion.bash:

# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty
# value, unstaged (*) and staged (+) changes will be shown next
# to the branch name. You can configure this per-repository
# with the bash.showDirtyState variable, which defaults to true
# once GIT_PS1_SHOWDIRTYSTATE is enabled.

Troubleshooting __git_ps1 Error

If you’re getting an error like -bash: __git_ps1: command not found in the command prompt and your branch name isn’t showing up in the command prompt, try sourcing the git-completion.bash that comes with your Git install (assuming you have installed Git via Homebrew, which I’d recommend for Mac users.) The code would look like something like this:

# git command autocompletion script
source /usr/share/git-core/git-completion.bash