Zsh: using color

Zsh color nonsense

This is a fairly random collection of notes to myself about using color in Zsh shell scripts.

Maybe you will find them useful.

Using colors in Scripts

Zsh ships with a cunningly named function named colors. It is a common function used in zsh scripts.

autoload -Uz colors && colors

It defines several associative arrays and variables.

The “main” arrays are color and its alias colour .

The arrays you actually use are fg, fg_bold , and fg_no_bold for the foregound and

bg, bg_bold, and bg_no_bold for the background.

Here is how to print a message in a particular color, bold red in this case.

The array indexes are keys from the color/colour array. reset_color does what it

says on the tin. Leave it out and see what happens

print -- $fg_bold[red]enter filename$reset_color

This will show the keys.

for k in ${color} do 
   print -- key: $k 

This might help seeing the relationships. 31 is the standard ANSI code for red.

color/colours holds these values and more.

print -- $fg[$color[31]]foo$reset_color 
# which is the same as 
print -- $fg[red]foo$reset_color

That 31 for red would be inserted into the ANSI escape code “ESC[31m”.

The array fg (and friends) holds these ANSI code values. If you don’t believe me, try this script.

for k in ${fg} do
     print -- key: $k

key: ESC[32m key: ESC[36m key: ESC[37m key: ESC[33m key: ESC[35m key: ESC[30m key: ESC[34m key: ESC[31m key: ESC[39m key: ESC[30m key: ESC[32m

Besides print , you can use color elsewhere. For example, here is a read snippet.

read -qs "answer?$fg_bold[green]$bg[blue]Do the thing? [yn] $reset_color" 

print ${answer} 

# probably use a case statement on $answer

Other attributes such as underline and blink are there, but they don’t work with

iTerm on macOS. For flakily supported things like this its better to avoid them.

Shell prompt color

The prompt syntax is a bit different. You can use it with print via the -P flag

if you want to test your prompt, or if you just like using its baroque syntax.

print -P -- "%F{red}%K{bg-blue}test string%k%f"

There are 1.6022 x 10^23 tutorials out there on customizing the zsh prompt, so

“that’s all I have to say about that”.


I just use Powerlevel10k to customize my prompt. If I’m in need of distraction, I’ll just edit my Emacs LISP instead of treading the zsh “theme” path.