Current Git Branch for your prompt
I guess most of you that use Git on a more regular base, like the easiness of creating, merging and deleting branches thats comes along with Git, so you will probably tend to create branch over branch. I often change into a Git repository and ask myself: which was the last branch I was working on? Of course you can simply call ‘git status’, but wouldn’t it be more convenient to promptly see in which branch you reside as soon as you enter the repository?
If you are answer is “yes” then you should take a look on bash completion – to be more exact: to the Git related part of it.
The Git bash completion script offers a function called __git_ps1. As the ps1 already indicates, the function is intended to be called in the PS1 definition of your .bashrc. Just open your .bashrc in your favourite editor and search for PS1= which might look like the following:
PS1='[\u@\h \W]\$'
whereby your shell prompt results in:
[username@hostname path]$
To add the current Git branch to your prompt simply add the __git_ps1 function to it:
PS1='[\u@\h \W $(__git_ps1 " (%s)")]\$'
The argument to __git_ps1 will be displayed only if you are currently in a git repository:
[username@hostname path (branchname)]$
Pimp your GIT prompt!
Let __git_ps1 also show if your branch is staged, unstaged, stashed or include an untracked file:
export GIT_PS1_SHOWDIRTYSTATE=1
# if GIT_PS1_SHOWDIRTYSTATE is set to a nonempty value,
# unstaged (*) and staged (+) changes will be shown next to the branch name
export GIT_PS1_SHOWSTASHSTATE=1
# if GIT_PS1_SHOWSTASHSTATE is set to a nonempty value,
# a ‘$’ will be shown next to the branch name if something is stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1
# if GIT_PS1_SHOWUNTRACKEDFILES is set to a nonempty value,
# a ‘%’ will be shown next to the branch name if there’re untracked files
export PS1=’\w$(__git_ps1 “(%s)”) > ‘