This is part 3 of my series on tricks I’ve used in shell scripts. In this post, I’ll share a few ways I’ve colorized text in shell scripts.

Terminals use escape codes to control colors. In Bash or ZSH scripts, these are typically expressed as \e ... or \033 ... (or sometimes ^[, although that is actually typed by pressing Ctrl-V, [, NOT ^, [). I tend to see more cases of \e than \033 in the wild.

An example of printing red text:

printf "\e[031m%s\e[0m\n" 'Danger is go!'

Running that should show:

Danger is go!

Here, \e031m is setting the 031 color, which is red text with no background. \e[0m sets the color back to the default, which is probably white or black text with no background, depending on your terminal theme.

It is important that you reset the text color. Otherwise all output will continue to be colorized. Depending on your shell configuration, even commands run after your script could be colorized inadvertently.

Here is a small script I found years ago that will show you what colors are available in your terminal:

# Usage: colordump
# Dump 256 ansi colors to the terminal.

printf "How each ANSI color is displayed on your terminal:\n\n"

while [ $i -lt 255 ];
    newrow=$(expr $i / 10)
    test $newrow -ne $row && printf "\n"
    printf "\e[%dm %03d \e[0m" $i $i
    i=$(expr $i + 1)

printf '\n\n     e.g., "\\e[41mTEXT\\e[0m" '
printf "\e[41m(for TEXT like this)\e[0m\n"

Run colordump to see a full list of colors available.

See also: