Display Colored Output in Shell Scripts

Submitted by jbreland on Fri, 06/18/2010 - 04:10

Most modern terminals* (xterm, Linux desktop environment terminals, Linux console, etc.) support ANSI escape sequences for providing colorized output. While I'm not a fan of flash for flash's sake, a little splash of color here and there in the right places can greatly enhance script output.

In Bash, I include the following functions in any script where I want colored output:

# Display colorized information output
function cinfo() {
	COLOR='\033[01;33m'	# bold yellow
	RESET='\033[00;00m'	# normal white
	MESSAGE=${@:-"${RESET}Error: No message passed"}
	echo -e "${COLOR}${MESSAGE}${RESET}"
}
 
# Display colorized warning output
function cwarn() {
	COLOR='\033[01;31m'	# bold red
	RESET='\033[00;00m'	# normal white
	MESSAGE=${@:-"${RESET}Error: No message passed"}
	echo -e "${COLOR}${MESSAGE}${RESET}"
}

This allows me to easily output yellow (cinfo) or red (cwarn) text with a single line in a script. Eg.:

cwarn "Error: operation failed"

If this message was output normally with echo and it was surrounded by a lot of other text, it might be overlooked by the user. By making it red, however, it's significantly more likely to stand out from any surrounding, "normal" output.

My most common use for these functions are simple status output messages. Eg., if I have a script or function that's going to do five different things and display output for each of those tasks, I'd like to have any easy way to visually distinguish each of the steps, as well as easily determine which step the script is on. So, I'll do something like this (from one of my system maintenance scripts):

# Rebuild packages with broken dependencies
cinfo "\nChecking for broken reverse dependencies\n"
revdep-rebuild -i -- -av
# Rebuild packages with new use flags
cinfo "\nChecking for updated ebuild with new USE flags\n"
emerge -DNav world

For more details, the Advanced Bash Scripting guide provides a detailed discussion on using ANSI escape sequences in scripts, both for color and other purposes. You can also find some additional info in the Bash Prompt HOWTO, as well as useful color charts on the Wikipedia page.

*Note: Traditional (read: old) Unixes generally don't support useful modern conveniences like this. If you regularly work with AIX or Solaris and the like, you may want to skip this tip.