Using Bash to Display Every Terminal Color and Text Style

Naman LadNaman Lad
2 min read

This one’s a quickie.

In the terminal, colors and text styles can make output more readable and visually appealing. Whether you’re creating a script with status messages or customizing your prompt, knowing how to use ANSI escape codes for colors and styles is invaluable.

In this post, let’s explore a simple Bash script that prints all possible combinations of colors and styles of text in the terminal, along with the respective codes that generate them.

The script

#!/bin/bash

for style in '' '1;' '2;' '3;' '4;' '9;'; do
    for fg in {30..37}; do
        for bg in {40..48}; do
            if [ -z "$style" ]; then
              echo -en "\x1b[${bg}m  \x1b[0m"
            fi

            echo -en "\x1b[${style}${fg};${bg}m ${style}${fg};${bg} \x1b[0m"
        done
        echo  # Newline after each row
    done
    echo # Newline after each style for separation
done

How it works

The outermost for-loop will iterate over different text styles.

  • ’’: This means no styling is added

  • 1: This will make the text bold

  • 2: This will make the text a little dim

  • 3: This will italicize the text

  • 4: This will add an underline to the text

  • 9: This will add a strikethrough to the text

The next for-loop iterates over all the foreground colors (30-37) and the next one over all the background colors (40-48).

The \x1b[0m resets the formatting of the text, so that each formatting is applied without affecting the next one.

Running the script

I named the file as ansi-test. Hence, I can run the following commands to execute the script:

chmod +x ansi-test
./ansi-test

This prints a grid displaying all possible combinations of colors and styles! 🎨

Where to find the code

I have uploaded this script to GitHub here so you can easily access and modify it. I have added the path to this directory to the $PATH variable on my machine, so I don’t have to navigate to this directory to execute it. I can just type ansi-test anywhere and can execute it 😉. I will share that piece of configuration in a future article. Until then, happy scripting!⚡

0
Subscribe to my newsletter

Read articles from Naman Lad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Naman Lad
Naman Lad