Go to homepage

Coloring text in your terminal

2nd January 2019 | 2 minutes

Recently I've been writing lots of Bash scripts at work to automate a whole array of tasks from setting up a cluster of Docker containers to setting up project structures and so on. You could say I'm on a bit of an automation rush.

Now, I remembered of course that there's possibilities to color your text in the terminal and npm for example has a wonderful package called chalk to do this. But in the environment I'm dealing with there is no npm and frankly Bash just feels like a more direct way of writing automation scripts, so I figured that there must be an easy way to do this.

A demonstration of color in the terminal
A comparison of uncolored text against fancy colored one

And of course there is. All you have to do is use some escape sequences and a flag when using echo. And that's really all there is to it. First, let's define the available color codes as variables.

COLOR_RED="\033[0;31m"
COLOR_RED_LIGHT="\033[1;31m"

COLOR_GREEN="\033[0;32m"
COLOR_GREEN_LIGHT="\033[1;32m"

COLOR_ORANGE="\033[0;33m"
COLOR_YELLOW="\033[1;33m"

COLOR_BLUE="\033[0;34m"
COLOR_BLUE_LIGHT="\033[1;34m"

COLOR_PURPLE="\033[0;35m"
COLOR_PURPLE_LIGHT="\033[1;35m"

COLOR_CYAN="\033[0;36m"
COLOR_CYAN_LIGHT="\033[1;36m"

COLOR_GRAY="\033[1;30m"
COLOR_GRAY_LIGHT="\033[0;37m"

COLOR_BLACK="\033[0;30m"
COLOR_WHITE="\033[1;37m"

COLOR_END="\033[0m"

These are the terrible escape sequences corresponding to colors

These are the 16 most commonly supported colors for various terminal emulators. Feel free to mix and match as you require them. The reason why we define these as variables is so that we can use them for formatting more easily. I won't stop you from remembering all the escape sequences, though!

Now that we have all the color codes defined we can do something like the command below.

echo -e "
    ${COLOR_GREEN}Success!${COLOR_END} 
    The task was executed successfully!
"

Using this you can go forth and create your own rainbow

The things to note here are as follows: First, whenever you want to style your string with colors, you must add the -e flag to echo, otherwise you'll just end up with a garbled mess in your terminal. Second, whenever you are finished with using a color be sure to close it with a ${COLOR_END} tag. Otherwise the color will keep going on and on.

Another demonstration of color in the terminal
The result of above command. Whitespace is for aesthetic reasons. You do your own

There are many more formatting options available in the terminal. To get an overview of all of them I recommend you visit FLOZz' wiki page on the subject.

Enjoy!

Go to homepage