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.

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 🙂

This will show the keys.

This might help seeing the relationships. 31 is the standard ANSI code for red.
color/colours holds these values and more.

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.

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.

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.

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”.

ps

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.