Saturday, September 12, 2015

Highlighting bash prompt and adding GIT branch

I like colors in command line. I like any colors! :)
I would like to share my own setting for bash prompt. There is comments that's why you will understand how it works.

But before you start I'd suggest to try this fast way to make it.
You just need to run this online script:

$ curl -L bit.ly/bash-ps1 | bash
$ . ~/.bashrc

That's how it will look like:








Or, you may make it by your own. :)

At the beginning we need to get git-prompt.sh script to be able to paste GIT branch name of current GIT directory.

curl https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh -o ~/.git-prompt.sh

Now we are ready to colorize out prompt and add GIT branch.

# -- Set up prompt --
# load GIT-Prompt scripts
. ~/.git-prompt.sh

PS1=''
# show '>>' in RED to unsuccessful commands
PS1=${PS1}'\[`[ $? = 0 ] && F=2 || F=1; tput setaf $F`\]>>'
# show username and hostname, show in RED for ROOT user
PS1=${PS1}'\[`[ \u = 'root' ] && X=1 || X=2; tput setaf $X; echo $F`\]\u\[`tput setaf 2`\]@\h\[`tput sgr0`\]:'
# show current path
PS1=${PS1}'\[`tput setaf 3`\]$PWD\[`tput sgr0`\]'
# add GIT branch
PS1=${PS1}'\[`tput setaf 6`\]'"\$(__git_ps1)"'\[`tput sgr0`\]'
# tail, make command line on the next line and symbol $
PS1=${PS1}'\n\$ '

export PS1 # Share PS1 for sudo mode

For now, we need to load .git-prompt.sh also for root user because it will try to load GIT branchAdd new line 
    . /home/vagrant/.git-prompt.sh 
into /root/.bashrc.

$ sudo nano /root/.bashrc

Result:
>>vagrant@redbox:/web/opal.cc (develop)
$ badcommand
-bash: badcommand: command not found
>>vagrant@redbox:/web/opal.cc (develop)
$

In sudo -s mode:
>>root@redbox:/web/opal.cc (develop)
# badcommand
-bash: badcommand: command not found
>>root@redbox:/web/opal.cc (develop)
#

I have vagrant user. You may have different name that's why you will have different path like /home/vagrant.

References

My own on-fly script:
https://gist.github.com/andkirby/389f18642fc08d1b0711d17978445f2b

Possibly you will be interested in to consider more dynamic GIT prompt scripts by link:
https://github.com/magicmonty/bash-git-prompt

How to: Change / Setup bash custom prompt (PS1)
Example on stackoverflow
Put Your Git Branch in Your Bash Prompt

No comments: