I frequently work on my source trees which is managed by git version control. For many times I worked on several files then I figured I was working on the incorrect checkout. Then I found out git provides some bash scripts which helps to auto complete your branch name and show the current branch name in the bash prompt (PS1).
However, in the git appendix A it shows a very ugly PS1 script. I like my original bash PS1 with the branch name and auto-complete, followed by the brach name in bright color. I paste my code here to remind myself and hopefully can help other people whom want to do the same.
- Download git-completion.bash from git source code. This file auto complete(using <tab> key) your branch name in your bash prompt:
$ wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash
- Download git-prompt.sh . This script shows your current branch name:
$ wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh
- $ source git-completion.bash
$ source git-prompt.sh
$ export PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\[\e[96m\]$(__git_ps1 "(%s)")\[\e[0m\]\$ '
Then it should turn PS1 like my prompt below:
gideon@gideon-i5:~/catkin_ws/src/turtlebot(indigo)$
To include the above scripts everytime you start your bash, change your .bashrc. I put the following lines to my .bashrc
source ~/.git-completion.bash
source ~/.git-prompt.sh
export GIT_PS1_SHOWDIRTYSTATE=1
# PS1 with git (line wrap issue fixed!!)
export PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\[\e[96m\]$(__git_ps1 "(%s)")\[\e[0m\]\$ '
As a note, in Bash, the <Esc> character can be expressed with the following syntaxes:
For example, \e[31m shows the following characters in
Red color. The ”\e[0m” sequence removes all attributes which can be used end the bash coloring. However, these <Esc> and color characters breaks the bash windone line wrap counts. That is why you need \[ and \] to state to bash that those are non-printing characters.
Yes those are not for human.... and if you understand what I said.... get a life!
References
https://git-scm.com/book/en/v2/Appendix-A:-Git-in-Other-Environments-Git-in-Bash
http://misc.flogisoft.com/bash/tip_colors_and_formatting
http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/nonprintingchars.html