In Linux, you can add some color to the output of the echo
command to make it more visually appealing. By using special escape sequences, you can customize the text color, background color, and text style.
Using Escape Sequences
Escape sequences are special character combinations that, when included in the echo
command, instruct the terminal to change the color and style of the text. The basic syntax for using escape sequences is \e[<CODE>m
.
-
\e
: The escape character. -
<CODE>
: The color/style code.
Color Codes
Here are some common color codes that you can use:
- Black:
\e[30m
- Red:
\e[31m
- Green:
\e[32m
- Yellow:
\e[33m
- Blue:
\e[34m
- Magenta:
\e[35m
- Cyan:
\e[36m
- White:
\e[37m
Text Style Codes
You can also apply text styles to the output:
- Bold:
\e[1m
- Underline:
\e[4m
- Blinking:
\e[5m
- Reverse (swap background and foreground colors):
\e[7m
- Reset (restore default text attributes):
\e[0m
Changing Output Color
Now, let's see how to change the output color of the echo
command using escape sequences:
Changing Text Color
To change the text color, add the color code before the text you want to display:
echo -e "\e[31mThis text will be displayed in red.\e[0m"
The \e[31m
sets the text color to red, and \e[0m
resets it back to the default color.
Applying Text Styles
You can also combine multiple attributes to style the output text:
echo -e "\e[1;33;44mThis text will be bold, yellow, and have a blue background.\e[0m"
In this example, \e[1;33;44m
sets the text to bold (1), yellow (33), and gives it a blue background (44).
Using Variables
If you want to use colors in variables, you need to use PS1
(prompt variable) and use echo -e
to interpret the escape sequences:
COLOR_RED="\e[31m"
COLOR_RESET="\e[0m"
text="This text will be red."
echo -e "${COLOR_RED}${text}${COLOR_RESET}"
Here, COLOR_RED
and COLOR_RESET
are variables holding the color codes, and ${COLOR_RED}
and ${COLOR_RESET}
are used to apply those colors to the echo
command.
0 Comment