Coloring text in your terminal
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.










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


Go to homepage