www.LinuxHowtos.org

edit this article

ANSI Escape Sequences Colors

This tip shows the colors available as ANSI escape sequences. These can be used to beautify terminal prompts, text, or anything else that understands ANSI escape sequences.

ANSI escape sequences are non-printed text that is interpreted to change the format of some text. In this example, we will specifically look at the use of escape sequences to specify colors. In the standard Gentoo /etc/profile, there are some examples of these colors already being used to change the color of parts of the terminal prompt. For example, the pathname appears in blue and parts of the bash prompt show up in red or green depending on whether you are root or a normal user.

Non-printable ANSI escape sequences are always enclosed \[\033[ and \]. Colors must be followed by a m. Using the example from /etc/profile, we can see that the color code for green is 32, the code for blue is 34, and the code for red is 31.

Code Listing 1: PS1 from /etc/profile

// root user 
export PS1='\[\033[01;31m\]\h \[\033[01;34m\]\W \$ \[\033[00m\]' 
                      red               blue 
// normal user 
export PS1='\[\033[01;32m\]\u@\h \[\033[01;34m\]\W \$ \[\033[00m\]' 
                      green                blue

The next part is the 1 preceding the actual color code. This indicates whether or not the color should be bold or not (0 for normal, 1 for bold). So if you wanted a normal green instead of a bold green, you would use 00;32m instead of 01;32m.

Note: This does not work with all colors. See the list at the bottom for a list of what's available in bold.

For background colors you would 4x instead of 3x. So to have the background blue instead of the text, you could use 00;44m instead of 01;34m.

Here is a list of colors and their escape sequences.
Code Listing 2

    Black      0;30       Dark Gray    1;30 
    Red        0;31       Bold Red     1;31 
    Green      0;32       Bold Green   1;32 
    Yellow     0;33       Bold Yellow  1;33 
    Blue       0;34       Bold Blue    1;34  
    Purple     0;35       Bold Purple  1;35 
    Cyan       0;36       Bold Cyan    1;36 
    Light Gray 0;37       White        1;37

Note: ANSI sequence 0;33 is listed as Brown in the BASH-Prompt HOWTO, but it seems more of a mustard yellow. Strictly speaking, the bold version of it is indeed yellow - therefore I've listed it as yellow.

From http://www.gentoo.org/news/en/gwn/20031201-newsletter.xml


rate this article:
current rating: average rating: 1.0 (7926 votes) (1=very good 6=terrible)
Your rating:
Very good (1) Good (2) ok (3) average (4) bad (5) terrible (6)

back