dizzle

ANSI Terminal Colors

So, I was playing with the awesome Mac utility BitBar and needed to show multiple colors on one line. I couldn't figure out how to do it using BitBar's "color=orange" syntax and since I only needed to echo out the info for BitBar to display, I turned to ANSI escape codes

You can go crazy with ANSI escape codes and terminal tricks but I'm just concentrating on colors for now.

Well, as usual I got sidetracked from my original BitBar project and ended up writing a small Bash script to display a bunch of ANSI terminal colors. I'm mean, I will definitely need this some other time right?

Now, I'm not great at Bash scripting but here's how I did it...

Let's Script This

First I setup the foreground color codes as named variables.

# TEXT COLOR
DEFAULT="\033[0m"
BLACK="\033[30m"
RED="\033[31m"
GREEN="\033[32m"
ORANGE="\033[33m"
BLUE="\033[34m"
PURPLE="\033[35m"
CYAN="\033[36m"
LIGHTGRAY="\033[37m"
DARKGRAY="\033[1;30m"
LIGHTRED="\033[1;31m"
LIGHTGREEN="\033[1;32m"
YELLOW="\033[1;33m"
LIGHTBLUE="\033[1;34m"
LIGHTPURPLE="\033[1;35m"
LIGHTCYAN="\033[1;36m"
WHITE="\033[1;37m"

Now that my foreground colors are set, I setup variables for the background colors as well.

# BACKGROUND COLOR
BG_DEFAULT="\033[049m"
BG_BLACK="\033[40m"
BG_RED="\033[41m"
BG_GREEN="\033[42m"
BG_ORANGE="\033[43m"
BG_BLUE="\033[44m"
BG_PURPLE="\033[45m"
BG_CYAN="\033[46m"
BG_LIGHTGRAY="\033[47m"
BG_DARKGRAY="\033[100m"
BG_LIGHTRED="\033[101m"
BG_LIGHTGREEN="\033[102m"
BG_YELLOW="\033[103m"
BG_LIGHTBLUE="\033[104m"
BG_LIGHTPURPLE="\033[105m"
BG_LIGHTCYAN="\033[106m"
BG_WHITE="\033[107m"

Next, I created an array of all available colors.

COLORS=("DEFAULT" "BLACK" "RED" "GREEN" "ORANGE" "BLUE" "PURPLE" "CYAN" "LIGHTGRAY" "DARKGRAY" "LIGHTRED" "LIGHTGREEN" "YELLOW" "LIGHTBLUE" "LIGHTPURPLE" "LIGHTCYAN" "WHITE")

And, finally I iterate through the COLORS array, grab the ansi codes from the variables I set and echo everything out to the screen.

for color in "${COLORS[@]}"
do
    bg_color="BG_"${color}
    echo -en ${!color}
    echo -n "${color} => ${!color} "
    echo -en ${!bg_color}
    if [ "$color" = "WHITE" ]; then
        echo -en ${BLACK}
    else
        echo -en ${WHITE}
    fi
    echo -n ${!bg_color}
    echo -e ${BG_DEFAULT}${DEFAULT}
done

ANSI Terminal Colors

Ohh, so colorful! 👀

I'm sure they are better ways to script this, but I'm pleased with the results as it gives me the info I need.

View the full script here