Awesome Sauce Bash Prompt Howto

TwitterDeliciousStumbleUponBlogger PostTechnorati FavoritesDiggLinkatopiaPingShare

Let’s get busy! Put the following lines in your ~/.bashrc or ~/.bash_profile and next time you open a terminal it should just work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
black=$(tput -Txterm setaf 0)
red=$(tput -Txterm setaf 1)
green=$(tput -Txterm setaf 2)
yellow=$(tput -Txterm setaf 3)
dk_blue=$(tput -Txterm setaf 4)
pink=$(tput -Txterm setaf 5)
lt_blue=$(tput -Txterm setaf 6)
 
bold=$(tput -Txterm bold)
reset=$(tput -Txterm sgr0)
 
arr_smiley_color=("$green" "$red")
arr_smiley_status=(":)" ":(")
export PS1='\n\[$bold\]\[$black\][\[$dk_blue\]\@\[$black\]]-[\[$green\]\u\[$yellow\]@\[$green\]\H\[$black\]]-[\[$pink\]\w\[$black\]]\[$reset\]\n\[${arr_smiley_color[$?>0]}\]${arr_smiley_status[$?>0]} \[$reset\]\$ '

It’s kind of complicated, but really pretty simple. There are sequences of characters that bash treats in a special way. Most notably some of them cause bash to change the color of its output in your terminal. You can use these special sequences (called escape codes) in your bash prompt to make things look cool.

You could memorize all the numbers and codes for each color or you could use the handy tput command to retrieve the various color codes for you. I’ve already done the work of labeling which number translates in to what style, so then all you need to do is use them in your prompt. All you need to remember is that each of these codes must be surrounded by \[ and \]. With that in mind, feel free to play with and change the colors all you like.

Swap out the different color names on line 14 to change it up and suit your taste. I’ve also got a fancy little bit of trickery as you’ll see there on lines 12 and 13. The prompt is evaluated after every command, and so we can actually check conditional expressions. In this case I’m checking to see if the last command failed or succeeded. If the previous command failed you get a red sad face, if it succeeded then you get a green happy face. This prompt also spans two lines as you can see by using the standard \n escape character for new line.

There are some other, bash prompt specific, escape characters used here that you may not have been aware of: the current time for example is \@. Check the bash manual pages for a complete list of the escape sequences available on the bash prompt.

TwitterDeliciousStumbleUponBlogger PostTechnorati FavoritesDiggLinkatopiaPingShare
This entry was posted in Tutorials and tagged , . Bookmark the permalink.

Comments are closed.

Rock Solid Web Design is a full service web development firm specializing in custom database driven applications in PHP.