Bash: Using Colors

How to use colors to display information in bash?

Use ANSI escape sequences to set text properties like foreground and background colors.

echo -e "\e[1;34mThis is a blue text.\e[0m"

Bash uses numeric codes to set attributes of the text to be displayed.

Attribute codes:
00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed

Text color codes:
30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white

Background color codes:
40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white

In the example above, me used the ANSI escape sequence \e[attribute code;text color codem to display a blue text. Therefore, we have to use -e option in calling echo to escape the input. Note that the color effect had to be ended by \e[0m to prevent the display of the prompt with different colors. However, the effects are sometimes interesting. I encourage you to play around with it.

To have a background, we must use the background color codes. The sequence then becomes \e[attribute code;text color code;background color codem. As you can guess, any missing code is simply taken as zero value by bash. Provided you shell supports 8-bit colors (the new Cygwin version 1.43 and a00.seng.engr do), you can display a colored welcome message when you log into bash by typing the following into your .bashrc:

green='\e[0;32m' # '\e[1;32m' is too bright for white bg.

# Display welcome message
echo -e "${green}Welcome \e[5;32;47m $USER \n${endColor}"

It is generally a good idea to define colors so that you can use them in anytime, anywhere in the shell session. To demonstrate this, I am defining green in .bashrc and accessing its value in echo. The username should appear with white background and green foreground, text color and should be surrounded by one space on each side. Note that I am also terminating the color effect by appending the value of endColor.

You could define a red color in .bashrc and display errors in red color in your scripts by doing something similar to the following example:

# swap: Swaps contents of two files
#    param1: the file to be swapped
#    param2: the file to be swapped
function swap() # swap 2 filenames around
   if [[ -e "$1" && -e "$2" ]]      # if files exist
      local TMPFILE=tmp.$$
      mv "$1" $TMPFILE
      mv "$2" "$1"
      mv $TMPFILE "$2"
      echo "\e[1;31mError:\e[0m Make sure the files exist."

So when you say something like the following, when the files don't exist:
swap file1 noFile or swap file1
you get an error statement highlighting that there has been an error.
Error: Make sure the files exist.

You can also customize or colorize your bash prompt. For more information see bash-customization-of-prompt..

I explored this myself but the color codes are taken from "/etc/DIR_COLORS" (in Cygwin).