The echo
command in Bash provides several options to control the formatting of the output. These options can be used to add colors, styles, and other formatting elements to the text.
Using Escape Sequences
One of the most common ways to format the output of the echo
command is by using escape sequences. Escape sequences are special character combinations that tell the shell to perform a specific action, such as changing the text color or applying bold or italic formatting.
Here are some common escape sequences that can be used with the echo
command:
Escape Sequence |
Description |
\e[0m |
Reset formatting to default |
\e[1m |
Bold text |
\e[4m |
Underlined text |
\e[31m |
Red text |
\e[32m |
Green text |
\e[33m |
Yellow text |
\e[34m |
Blue text |
\e[35m |
Magenta text |
\e[36m |
Cyan text |
To use these escape sequences, you can simply include them within the echo
command:
echo -e "\e[1mBold Text\e[0m"
echo -e "\e[31mRed Text\e[0m"
This will output:
Bold Text
Red Text
Using the -e Option
By default, the echo
command does not interpret escape sequences. To enable the interpretation of escape sequences, you need to use the -e
option:
echo "This is \e[1mBold\e[0m text."
This will not work as expected, as the escape sequences will be printed literally. To make it work, you need to use the -e
option:
echo -e "This is \e[1mBold\e[0m text."
This will output:
This is Bold text.
You can also combine multiple formatting options to achieve more complex formatting:
echo -e "\e[1;4;31mBold, Underlined, Red Text\e[0m"
This will output:
Bold, Underlined, Red Text
By understanding how to use escape sequences and the -e
option, you can create visually appealing and informative output in your Bash scripts.