Add some colour to your scripts

After writing a short script to check the amount of free space on the file system containing my home folder each time I login I decided that I would really like to make the fact that I was running out of disk space stand out a bit using colour.

Since the linux console and most terminal windows support ANSI escape sequences you can do this by including the required escape sequence in any text sent to standard output or standard error. Escape sequences begin with an escape character which can be specified using hexadecimal, octal or a special character and an open square bracket.

Note – You need to enable interpretation of any escape sequences using ‘-e’.

Using an escape sequence you can modify the colour, background, and style of any output text.

$ echo -e "\x1b[0;36mwibble\x1b[0m"     # Cyan text
wibble
$ echo -e "\033[0;42mwibble\033[0m"     # Green background
wibble
$ echo -e "\e[1;31mwibble\e[0m"         # Bright red text
wibble
$

 
You can also combine codes together including background colour, foreground colour and multiple attributes.

$ echo -e "\e[0;31;42mwibble\e[0m"      # Red text on a green background
wibble
$ echo -e "\e[0;37;40mwibble\e[0m"      # Grey text on a black background
wibble
$ echo -e "\e[0;7mwibble\e[0m"          # Inverse video
wibble
$ echo -e "\e[4mwibble\e[0m"            # Underlined text
wibble
$ echo -e "\e[4;31mwibble\e[0m"         # Underlined red text
wibble
$ echo -e "\e[1;4;31mwibble\e[0m"       # Bold underlined red text
wibble
$ echo -e "\e[1;4;31;42mwibble\e[0m"    # As above with a green background
wibble
$ echo -e "\e[7;1;4;31;42mwibble\e[0m"  # Inverse of the above
wibble
$

The original script that checks to see if there is less then 15% free space on the current filesystem is shown below.

# /bin/bash
#
# check-freespace.sh
#
# Checks to see if the current folder is on a file system with less than the
# specified percentage of free space and prints a warning if it is.
#
# 22 Dec 15 – 0.1   – Initial version – MEJT
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
_threashold=15
#
_free=($(df -k .|grep \/dev| tr -s ' ' |tr -d '%' | cut -d ' ' -f 5))
if [[ "$(($_free-$_threashold))" -lt "0" ]]; then
   echo "Warning - Less than ${_threashold}% free space remaining"
fi
#

 
You can just use the escape sequences directly but it is easier to see what is going on in a script if they have meaningful names. The modified script below prints the ‘Warning’ texct in red to make it stand out.

#!/bin/bash
#
# check-freespace.sh
#
# Checks to see if the current folder is on a file system with less than the
# specified percentage of free space and prints a warning if it is.
#
# 22 Dec 15 – 0.1   – Initial version – MEJT
# 24 Dec 15 – 0.2   – Added colour to warning message – MEJT
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
_black="\e[0;30m"                        # Normal black text
_red="\e[0;31m"                          # Normal red text
_green="\e[0;32m"                        #   :
_yellow="\e[0;33m"                       #   :
_blue="\e[0;34m"                         #   :
_magenta="\e[0;35m"
_cyan="\e[0;36m"
_white="\e[0;37m"
_normal="\e[0m"                          # Revert to normal

_BLACK="\e[1;30m"                        # Bold black text
_RED="\e[1;31m"                          # Bold red text
_GREEN="\e[1;32m"                        #   :
_YELLOW="\e[1;33m"                       #   :
_BLUE="\e[1;34m"                         #   :
_MAGENTA="\e[1;35m"
_CYAN="\e[1;36m"
_WHITE="\e[1;37m"
#
_threashold=15
#
_free=($(df -k .|grep \/dev| tr -s ' ' |tr -d '%' | cut -d ' ' -f 5))
if [[ "$(($_free-$_threashold))" -lt "0" ]]; then
   echo -e "${_RED}Warning${_normal} - Less than ${_threashold}% free space remaining"
fi
#

 
To see the effect of the escape sequences in the script save it, make it executable and run it.

$ chmod +x check-freespace.sh
$ ./check-freespace.sh
Warning – Less than 15% free space remaining
$

Obviously it won’t display a message unless there is less free space on the file system than specified by the threshold value!

To see what effects can be achieved you can use the following script to display all the standard combinations possible using ANSI escape sequences.

#!/bin/bash
#
# print-ansi-codes.sh
#
# Displays a table showing all the common ANSI escape sequences that can
# be used to modify the text colours on an ANSI terminal.  The exact shade
# shown will depend on the terminal type.
#
# Based on <http://wiki.bash-hackers.org/scripting/terminalcodes>
#
# 12 Dec 15 – 0.1   – Initial version – MEJT
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# Note¹ – When displayed on an xterm the bold coloured text
# uses characters that are actually wider than the normal,
# so a tab character is used to make sue that the columns
# line up neatly.
#
# Note² – If you want white text on a coloured background
# and don’t want the characters to be a different width then
# use the reverse video attribute instead.
#
# Text Attributes:
#   0 Reset
#   1 Bold
#   2 Dim
#   3 Italic – Not widely supported
#   4 Underscore
#   5 Blink – Usually ignored on non DEC terminals
#   6 Blink (fast) – Not widely supported
#   7 Reverse
#   8 Hidden – Only useful for hiding input
#   9 Strikethrough
#
# Colours:
#   0 Black
#   1 Red
#   2 Green
#   3 Yellow
#   4 Blue
#   5 Magenta
#   6 Cyan
#   7 White
#   8 Custom – Not widely supported
#   9 Default
#
# Note³ – Prefix colour with a three to set the foreground
# colour or a four to set the background colour.
#

display()
{
for a in 0 1 2 3 4 5 7 9; do
  echo “a=$a
  for (( f=0; f<=8; f++ )) ; do
    for (( b=0; b<=8; b++ )) ; do
      #echo -ne "f=$f b=$b " # Print foreground and background codes
      echo -ne "\\e[${a};3${f};4${b}m"
      echo -ne "ESC[${a};3${f};4${b}m"
      echo -ne "\\e[0m "
    done
    echo
  done
  echo
done
echo
}
#

case "$TERM" in
  xterm*|rxvt|ansi|vt10*|linux)
    display
    ;;
  *)
    echo "Not an ANSI capable terminal"
    ;;
esac

If you really want to you can specify your own custom colours, but support for this depends on the type of terminal you are using.

Advertisements
This entry was posted in Debian, Linux, Raspbian, Ubuntu and tagged . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s