Bash – Change the color of the file name text

bashcolorsfilenameslinuxshell

I am writing scripts to initialize and configure a large system with many components.
Each component has its own log file.

I would like to change the color of the component file name to red whenever an error
occur on its installation/configuration.

How can I do it?

Best Answer

Google will find you the answer. Print Hello world in red:

echo -e "\033[0;31mHello world\033[0m"

Explained

<esc><attr>;<foreground>m

<esc>        = \033[  ANSI escape sequence, some environments will allow \e[ instead
<attr>       = 0      Normal text - bold possible with 1;
<foreground> = 31     30 + 1 = Color red - obviously!
m            = End of sequence

\033[0m       Reset colors (otherwise following lines will be red too)

Look at http://en.wikipedia.org/wiki/ANSI_escape_code for full list of colors and other functions (bold etc).

The command tput, if available, will make life easier:

echo -e "$(tput setaf 1)Hello world$(tput sgr0)"

Can even save sequences in vars for simpler use.

ERR_OPEN=$(tput setaf 1)
ERR_CLOSE=$(tput sgr0)
echo -e "${ERR_OPEN}Hello world${ERR_CLOSE}"
Related Question