How to Use Bash Echo with Color

Echo is the command to display the text or variable in the script’s output. However, the “echo” command is not limited to the output print as you can do different things including adding color to the output. If you change the output’s color, it improves the readability of the information.

Moreover, you can use a few additional options with the “echo” command to change the output colors. In this blog, we will explain all these ways to use the Bash echo with color in Linux.

How to Use the Bash Echo with Color

Using different colors with echo in Bash helps enhance a text’s visibility and highlight an important text. Enter the following command while using echo:

echo -e “e[1;32mThis line of text is Greene[0m”

  • The “-e” option enables the “echo” command to identify and interpret the escape sequences accordingly.
  • The e[1;32m is the ANSI code for green color.
  • The e[0m is the code for no color which we add at the end of the line to reset the text color.

ANSI Escape Codes

Now, you might wonder about the codes of colors other than green. So, here is the list of all the basic colors and their ANSI codes:

  • Black: e[0;30m
  • Red: e[0;31m
  • Green: e[0;32m
  • Yellow: e[0;33m
  • Blue: e[0;34m
  • Magenta: e[0;35m
  • Cyan: e[0;36m
  • White: e[0;37m

Bold Text

In case you want to make the text bold, replace “0” with “1” in the color code. For instance, use the command as follows:

echo “e[1;34mThis is an example of Cyan Bold texte[0m”

Changing theBackground Color

If you want to change the color of the text’s background instead, use the prefix 4 in place of 3 after the colon (;). For example:

echo -e “e[0;42mThis text has a green backgrounde[0m”

To make the text bold in the previous example, use the following:

echo -e “e[1;42mThis is a bold text having green backgrounde[0m”

Using Variables

Entering these codes repeatedly can be tiring. Thus, let’s look at an approach to make this process easy. Here, we will declare some variables and assign them the color codes according to the colors that we want. You need to do this once in a terminal session.

green=‘e[0;32m’

reset=‘e[0m’

echo -e ${green} This is a green text${reset}

Summary

The “echo” command is not constrained to only show a text. There are ways in which you can change the color of your text. In this quick guide, we discussed about using the Bash echo with color. It starts with a simple “echo color” command. Then, we see the ANSI codes for different colors. Furthermore, we also explained how to make the colored text bold and change the text’s background color.

source

Leave a Comment