Scripting‎ > ‎Linux shell‎ > ‎

Bash tips: echo output with colour

Thank you for visiting this page, this page has been update in another link Bash tips: echo output with colour
Most of time you don't need echo output with color, but if you have monitoring script, you want to high light you output with colors.

echo with -e option enable the parsing of the escape sequences.

Example one:

-e "\e[31mHello ITmyshare\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

The ”\e[0m” sequence removes all attributes (formatting and colors).

The examples in this page are in Bash but on terminals compatible with escape sequences can be used in every programming languages.

More color codes below:
Black       0;30     Dark Gray     1;30
Blue        0;34     Light Blue    1;34
Green       0;32     Light Green   1;32
Cyan        0;36     Light Cyan    1;36
Red         0;31     Light Red     1;31
Purple      0;35     Light Purple  1;35
Brown       0;33     Yellow        1;33
Light Gray  0;37     White         1;37
You can find out more codes for colors and formatting stuff with echo on compatible terminals, but I found most useful part is color part. You could see some formatting attribute not working on some terminals, for example: 05 blink .

Here are two simple function examples in my check script, which check node device, filesystem, database and application status. You can easily do similar thing to have a quick check for your application status, filesystem, and devices etc.. Drop me an e-mail if you want more.

postgreschk() {
  stat=`$pgchk status | awk '{ if (NF == 4) print $4; else print $2}'`
  if [ $stat == "running..." ] ; then
    if [ $debug -eq 1 ] ; then
        echo -e "\e[0;32m Succeed \e[0m $pgchk is $stat"
    echo -e "\e[0;31m Error! \e[0m $pgchk is $stat"

mysqlchk() {
  stat=`$mysqlchk status | awk '{ if (NF == 5) print $5; else print $3}'`
  if [ $stat == "running..." ] ; then
    if [ $debug -eq 1 ] ; then
        echo -e "\e[0;32m Succeed \e[0m $mysqlchk is $stat"
    echo -e "\e[0;31m Error! \e[0m $mysqlchk is $stat"