Saturday, March 18, 2006

Pimp Your Shell

Bored with your black and white Linux prompt? Try these tips to pimp your shell prompt for St. Patrick's day.
I tested these tips with Bash shell version 2 and above.
Most of the time, when working in s shell we see the following shell staring back at us:


bash-2.04$

If you happen to be root, you have the a "nicer" prompt:

bash-2.04#

In fact, several Linux distributions have tried to replaced this boring prompt with more colorful and informative ones.

The basic:
You change the prompt's appearance at the command line by:

%export PS1=”%”


This will create a prompt with exactly one character “%” staring at you.
So if you export

%export PS1=”Hello Worl%”

Your prompt will become:

Hello World%

This is interesting but it's just dry and static text. Why don't we add some additional info like username, current path and hostname into our prompt?

%export PS1="\u@\H%\w%"

This will give us the following prompt:

dly@nhatrang%~/download%

You get the picture? You can pretty much tell bash to display everything at the prompt. Those available infomation like current user name, hostname or current path are indicated by the slash "\" like C syntax!
If you want some more fancy stuff in your prompt here is the list:

\d Date in "Wed Sep 06" format
\e ASCII escape character
\h First part of hostname (such as "mybox")
\H Full hostname (such as "mybox.mydomain.com")
\s The name of the shell executable (such as "bash")
\t Time in 24-hour format (such as "23:01:01")
\T Time in 12-hour format (such as "11:01:01")
\@ Time in 12-hour format with am/pm

\u Your username
\w Current working directory (such as "/home/drobbins")

\W The "basename" of the current working directory (such as "drobbins")

\$ If you are not root, inserts a "$"; if you are root, you get a "#"

How do I color my prompt?

Adding color is simple. first, we design a prompt without color. Then we add some special escape sequences recognized by the shell to display part of the text in color. Usually, there are background and foreground colors, bold or not. And we have 8 colors to choose from.
Colors are selected by sandwiching numeric values between a "\e[" and a "m".
If we specify more than one numeric code, we separate each code with a semicolon. Here's an example color code:

"\e[32;40m"

So if we want to pim the previous prompt, it would be:

%export PS1="\e[32;40m\u@\H%\w%"

With 32 as the foreground color and 40 as the background color.
Look at this
grid as for your color reference.



This should yield the following format:
dly@nhatrang~/download%

We don't need to include the background color setting of 40 as black is the default color already.
What if you want to bolden the text, simply insert "1" which means brighter, bolder text.

%export PS1="\e[32;1m;\u@\H%\w%"

To get

dly@nhatrang~/download%

No comments: