The echo command in Linux is used to display a string or a set of strings onto the terminal. The string(s) is passed as an argument to the command. The echo command also comes with a set of options to manipulate how the output is displayed.
Terminals usually have default themes with light-colored text on a dark background or dark-colored text on a light background. Users can even customize it more based on preference. The echo command also displays text based on the color of the text defined in the theme.
In this article, we will see how to modify the output color of the echo command in Linux. For demonstrations, I will be using Ubuntu 20.10, however, this should work well on any other Linux distribution as well.
Modifying Output Color of Echo Command
There are escape sequences (some defined set of characters) that can be used on a Linux terminal to modify the color of the output.
The string to be colored should be preceded with the escape sequence:
Eg. If you want to output it red, it should be:
'\e' signifies the start of the escape sequence,
'[1' makes the text bold,
31 is the color code for red, and
'm' signifies the end of the escape sequence.
$ echo -e "\e[1;31mHello World!"
Notice that I passed the flag ‘-e’ as well. This flag will enable the echo command to consider the escape sequences in the string. Without the flag, an echo will print the characters
You can also use multiple colors for different substrings.
$ echo -e "\e[1;31mHello \e[1;35mWorld!"
The colors in the range 30-39 are for the foreground, i.e. the text. If you want to change the background color, you can do so by using the colors of codes 40 and above.
$ echo -e "\e[1;41mHello World!"
You can see that the background color Red has not only been applied on the text, but also on the console prompt string. To prevent this, end your echo string with an escape string with no color code.
$ echo -e "\e[1;41mHello World!\e[1;m"
You can use many more colors for your string. The list of colors is as follows:
In this article, we learned how to change the color of output when using the echo command in Linux. Note that while there is a standard built-in implementation of echo in Linux, every interpreter has its own echo command as well, which overrides the default implementation.
You can check the man page of your interpreter to learn if there are any differences to the echo command while printing text in color.
If you have any questions or feedback, feel free to leave a comment below!