7

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?

3 Answers 3

10

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}"
2

If you have an interest in setting colors as variables the following may be helpful for setting a color panel for bash scripting

COL_BLACK="\x1b[30;01m"
COL_LIGHTBLACK="\x1b[30;11m"
COL_BLUE="\x1b[34;01m"
COL_LIGHTBLUE="\x1b[34;11m"
COL_CYAN="\x1b[36;01m"
COL_LIGHTCYAN="\x1b[36;11m"
COL_GRAY="\x1b[37;11m"
COL_LIGHTGRAY="\x1b[37;01m"
COL_GREEN="\x1b[32;01m"
COL_LIGHTGREEN="\x1b[32;11m"
COL_PURPLE="\x1b[35;01m"
COL_LIGHTPURPLE="\x1b[35;11m"
COL_RED="\x1b[31;01m"
COL_LIGHTRED="\x1b[31;11m"
COL_YELLOW="\x1b[33;01m"
COL_LIGHTYELLOW="\x1b[33;11m"

COL_RESET="\x1b[39;49;00m"
1
  • Adam (above) has a nice explanation of how this works
    – E1Suave
    Apr 18, 2012 at 19:45
1

http://webhome.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html.

This may be what you want.

So you can get $? of the process of one component file, then choose to use

echo -e "\e[1;31m"<the-component-file-name>\e[0m"

to make its text red.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .