Bash color codes in Shell Script | Linux
Character color is controlled by sending the terminal emulator an ANSI escape code embedded in the stream of characters to be displayed. The control code does not “print out” on the display; rather it is interpreted by the terminal as an instruction. An ANSI escape code begins with an octal 033 (the code generated by the ESC key), followed by an optional character attribute, followed by an instruction. For example, the code to set the text color to normal (attribute = 0) black text is \033[0;30m.
Notice that the colors are divided into two groups, differentiated by the application of the bold character attribute (1), which creates the appearance of “light” colors.
Escape Sequences Used to Set Text Colors
Sequence Text Color |
\033[0;30m Black |
\033[0;31m Red |
\033[0;32m Green |
\033[0;33m Brown |
\033[0;34m Blue |
\033[0;35m Purple |
\033[0;36m Cyan |
\033[0;37m Light Gray |
\033[1;30m Dark Gray |
\033[1;31m Light Red |
\033[1;32m Light Green |
\033[1;33m Yellow |
\033[1;34m Light Blue |
\033[1;35m Light Purple |
\033[1;36m Light Cyan |
\033[1;37m White |
Let’s try to make a red prompt (seen here as gray). We’ll insert the escape code at the beginning:
<me@linuxbox ~>$ PS1=”\[\033[0;31m\]<\u@\h \W>\$ ”
That works, but notice that all the text that we type after the prompt is also red. To fix this, we will add another escape code to the end of the prompt that tells the terminal emulator to return to the previous color:
<me@linuxbox ~>$ PS1=”\[\033[0;31m\]<\u@\h \W>\$\[\033[0m\] ”
<me@linuxbox ~>$
It’s also possible to set the text background color using the codes listed in Table
The background colors do not support the bold attribute.
Sequence Background Color |
\033[0;40m Black |
\033[0;41m Red |
\033[0;42m Green |
\033[0;43m Brown |
\033[0;44m Blue |
\033[0;45m Purple |
\033[0;46m Cyan |
\033[0;47m Light Gray |
We can create a prompt with a red background by applying a simple change to the first escape code:
<me@linuxbox ~>$ PS1=”\[\033[0;41m\]<\u@\h \W>\$\[\033[0m\] ”
In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.