How to add color to your bash script

Bash scripts are very easy way to get things automated, and there are plenty of features to interact with the user. Apart from interacting you can also convey the information using colors. Just like this

1color

For getting colors in echo command you need to give escape sequence which tells the terminal to listen to a command to change the property of the terminal. For that you need to enable it using the parameter -e. Now to tell the terminal that we need to change the color, we have to send the command octal 033 or hexadecimal 0x1b.  For more informaition refer https://en.wikipedia.org/wiki/ANSI_escape_code .

echo -e "\033[31m Hello World"

The above example will change the text color in to red. 30-37 sets foreground color  40-47 sets background color. Now you can write scripts like to make the work easier.

 


ESC_SEQ="\x1b["
 COL_RESET=$ESC_SEQ"39;49;00m"
 COL_RED=$ESC_SEQ"31;01m"
 COL_GREEN=$ESC_SEQ"32;01m"
 COL_YELLOW=$ESC_SEQ"33;01m"
 COL_BLUE=$ESC_SEQ"34;01m"
 COL_MAGENTA=$ESC_SEQ"35;01m"
 COL_CYAN=$ESC_SEQ"36;01m"

 echo -e "$COL_RED This is yellow $COL_RESET"
 echo -e "$COL_BLUE This is red $COL_RESET"
 echo -e "$COL_YELLOW This is blue $COL_RESET"

The COL_RESET=$ESC_SEQ”39;49;00m” will reset the previously set property of the terminal and set it to default.

For more information check out the following links

http://misc.flogisoft.com/bash/tip_colors_and_formatting

http://wiki.bash-hackers.org/snipplets/add_color_to_your_scripts

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *