Simple terminal text formatting with tput
When writing shell scripts, I'd often resort to using hardcoded ANSI escape codes to format text, such as:
This shell snippet above shows how to add text formatting and color to shell script output via ANSI escape codes. It defines a few variables that contain different escape codes for bold, unbold, foreground, and background colors. Then, we echo two log messages with different colors and formatting options.
The first message is printed in bold red text on a yellow background, while the second message is printed in white text on a blue background. To ensure that subsequent output is not affected by the previous formatting, the RESET variable is used to reset all color and formatting options back to their defaults after each message is printed. The -e option is used with echo to enable the interpretation of backslash escapes, which includes the ANSI escape codes.
While this works fairly well, every time I have to write a fancy shell script, I have to either look up the ANSI color codes, copy-paste from an existing script, or explain to an LLM what I need. Then chatGPT serendipitously recommended a shell tool called tput that makes this workflow quite a bit better. Underneath tput also uses ANSI escape codes to control various text formatting options but it doesn't require you to hardcode these ugly escape codes.
Basic usage
The basic syntax of the tput command goes as follows:
Formatting options
Here are some commonly used tput formatting options:
- setaf : set the foreground (text) color to a specific color. For example, setaf 1 sets the color to red, while setaf 2 sets the color to green.
- setab : set the background color to a specific color.
- bold: set the text to bold.
- sgr0: reset all formatting options to their defaults.
- smul: underline the text.
Example usage
Running the script will give you the following output:

This also hardcodes the color and formatting codes but it's much easier than having to remember or search for the ANSI escape codes. Currently, I'm using a 256-bit macOS terminal and it supports fairly large sets of formatting options. You can run man tput to find out other features that are supported by your terminal. The following loop will print all the supported colors:
On my terminal, it prints this nice color palette:

Discussion in the ATmosphere