I normally work on multiple branches of a git repository and I tend to forget which branch I am currently in. If I don’t do ‘git branch‘, I sometimes make changes in the code and then realize that – Ah! this change should have been in a different branch. So I thought of adding a string to the command prompt which indicates which git branch I am in whenever I am in git repository branch directory. I Googled for this problem and got many solutions.
So currently I am using the following command prompt -
PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\033[01;37m\]\$(git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/{\1}/')\[\033[00m\]\$ "
The git branch part is -
\$(git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/{\1}/')
Explanation -
The command git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/{\1}/' is executed every time you press enter on command prompt.
git branch – outputs all the branches with an asterisk on the current branch if you are in a git repository directory. Now the problem is if you are not in a git repository directory executing this command will give you an error. There is no side effect but you won’t like to see an error every time you press enter on command prompt.
To remove the error 2>/dev/null is added which redirects all error messages to /dev/null.
To get the current branch output of git branch is piped to grep -e '\* ' which outputs the string containing '* ' (asterisk followed by a white space). The current branch is indicated by '* ' (asterisk followed by white space) in the beginning of the string.
Now to remove the '* ' from the string to get the branch name output of grep is piped to sed 's/^..\(.*\)/{\1}/'. This command magically removes the first two characters of the string and surrounds the string with {}. To know how this magic happens refer to backreferences and remembering pattern and sed substitutions.
If you use a better command prompt to indicate git branch please comment to let me know.