Bring colors to the prompt

It’s been a long time since we played with ANSI prompt in DOS. Colors, positions, shortcuts assigned to function keys etc.

And if you’re using a linux based workstation for development, it might get confusing with plenty of terminal windows open (I like Terminator terminal app a lot), usually filling the whole secondary monitor. This, this is only a simple version of a multi-window setup:

As you see, this guy had the same idea that the command prompt should be visible. It should stand out, give information at a glance. For each window I need to know on WHICH machine I’m currently logged in, WHO am I in terms of user and a basic idea of WHERE I am would be great.

So, how do we achieve this? We have to program the prompt sequence with color codes and information bits, write it into a script and execute it each time you start a new terminal window on the machine. ~/.bashrc is the place to look into!

Prompt is constructed form different parts, read more about it here. We are going to change only the PS1 part.

Colors

Check this for the color codes. What I do is I create some shrotcuts – this way the prompt sequence is quickly readable and easy to edit. Put these (and others, if you so wish) right at the end of the file.

yellow=$(tput setaf 3)
green=$(tput setaf 2)
gray=$(tput setaf 0)
red=$(tput setaf 1)
white=$(tput setaf 7)
reset=$(tput sgr0)
light=$(tput bold)

Now, how to use it? Whenever you start with a color, you either have to change it to a different color or reset it. These shortcuts variables have to be addressed with a $ sign and within the square brackets. Because we’re writing this in a script, we have to escape each “special” code or shortcut with a backslash.

Example:

PS1='\[$green\]\w\ $ \[$reset\]'

This will print your working directory in green color, a dollar sign in green, a space and then it will the reset the colors, so your command will be the default color.

prompt-example

Extra info – GIT

As a developer I like to know, if the current working directory is within a git repository, what branch am I in and what’s its state. Check the following script: https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh. Copy it to your home directory, following the instructions contained within (point 1, 2 and 3a).

This is my preferred prompt now:

PS1='\[$green\]\u\[$white\]:\[$reset\]\[$light$white\]\w\[$red\]$(__git_ps1)\[$yellow\] $ \[$reset\]'

prompt

And this is the part how I get it to work. Add this at the end of your ~/.bashrc file:

yellow=$(tput setaf 3)
green=$(tput setaf 2)
gray=$(tput setaf 0)
red=$(tput setaf 1)
white=$(tput setaf 7)
reset=$(tput sgr0)
light=$(tput bold)

source ~/git-prompt.sh

PS1='\[$green\]\u\[$white\]:\[$reset\]\[$light$white\]\w\[$red\]$(__git_ps1)\[$yellow\] $ \[$reset\]'

Leave a Reply