How do you add color or bold the echo outputs in a shell script?

If you’re working in linux you will be introduced to writing shell scripts at some point. When you do, you’ll become very familiar with the echo.

If you open your terminal, and run an echo command it’ll literally echo whatever you put after the echo:

$ echo "Hello World" Hello World

In short, it outputs whatever string you place after the echo.

At some point, in your bash script you will use an echo command to output a state. You will apply a setting or run a too, and you will use an echo to output the state on your screen. When you do this, you will want to add some form of readability to the output. You can do this with spacing, colors, or other similar syntax modifications. Similar to what you might find in this post (e.g., bold to highlight things of importance).

Doing this in a shell script is a bit different.

When trying to use colors you have to use the ANSI escape codes. Example:

Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Brown/Orange 0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37

In your bash script you’ll need to define the constant before you can use them.


NC='\033[0m' # No Color

This allows you to use it later in the script. In this example I’ve added a RED and a NC constant. This is important, and will make sense in the next section.

Now let’s make Hello red, and World black on the output. To do this, we’ll do the following in the script:


NC='\033[0m' # No Color

echo -e "${RED}Hello${NC} World"

What you see is that in order to call the Red constant you have to use ${RED}. You should also notice the use of the NC constant, ${NC}. This is important, if you don’t use it the red will apply to the rest of the echo output. The NC constant tells the color when to stop. Another important thing to make not of is the use of the -e option (definition: enable interpretation of backslash escapes). If you don’t use the e option you won’t be able to use the colors.

Now let’s say you want to add some bold to Hello. You have to add two additional constants:


NC='\033[0m' # No Color
BOLD=$(tput bold)
NORM=$(tput sgr0)

echo -e "${RED}${BOLD}Hello${NC}${NORM} World"

What we’ve done here is used the tput and the associated character attributes. In this instance we’re using bold and sgr0. We use the constants the same as the colors, but be mindful of the order. Similar to the color, you have to tell the output when to stop applying the character attribute.

In other words, if you don’t close the ${BOLD} with ${NORM} your entire output will be bold.

That should do it! Happy echo output formatting!

Sharing is caring!

Leave a Reply