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:
Run colordump
to see a full list of colors available.
See also: http://bluesock.org/~willg/dev/ansi.html