To change the output color of echo
in Linux, you use ANSI escape codes embedded in the string. These codes allow you to set text color, background color, and text styles (e.g., bold, underline). Here’s how to do it:
1. Basic Syntax
Use the following format in your echo
command:
echo -e "\e[<COLOR_CODE>m<YOUR_TEXT>\e[0m"
-e
enables interpretation of backslash escapes (required for ANSI codes).\e[
or\033[
starts the ANSI code sequence.<COLOR_CODE>m
defines the color/style (see tables below).\e[0m
resets the text to default.
2. Text Color Codes
Code | Color | Example |
---|---|---|
30 | Black | echo -e "\e[30mBlack Text\e[0m" |
31 | Red | echo -e "\e[31mRed Text\e[0m" |
32 | Green | echo -e "\e[32mGreen Text\e[0m" |
33 | Yellow | echo -e "\e[33mYellow Text\e[0m" |
34 | Blue | echo -e "\e[34mBlue Text\e[0m" |
35 | Magenta | echo -e "\e[35mMagenta Text\e[0m" |
36 | Cyan | echo -e "\e[36mCyan Text\e[0m" |
37 | White | echo -e "\e[37mWhite Text\e[0m" |
3. Background Color Codes
Code | Background Color | Example |
---|---|---|
40 | Black | echo -e "\e[44;37mBlue BG, White Text\e[0m" |
41 | Red | echo -e "\e[41mRed Background\e[0m" |
42 | Green | echo -e "\e[42mGreen Background\e[0m" |
43 | Yellow | echo -e "\e[43mYellow Background\e[0m" |
44 | Blue | echo -e "\e[44mBlue Background\e[0m" |
45 | Magenta | echo -e "\e[45mMagenta Background\e[0m" |
46 | Cyan | echo -e "\e[46mCyan Background\e[0m" |
47 | White | echo -e "\e[47mWhite Background\e[0m" |
4. Text Style Codes
Code | Style | Example |
---|---|---|
1 | Bold | echo -e "\e[1mBold Text\e[0m" |
2 | Dim | echo -e "\e[2mDim Text\e[0m" |
4 | Underline | echo -e "\e[4mUnderlined\e[0m" |
5 | Blink | echo -e "\e[5mBlinking\e[0m" |
7 | Invert | echo -e "\e[7mInverted\e[0m" |
5. Combining Styles and Colors
Combine codes with semicolons (;
):
echo -e "\e[1;31;42mBold Red Text on Green Background\e[0m"
1
= Bold,31
= Red text,42
= Green background.
6. Using printf
Instead of echo
For better compatibility (especially in scripts):
printf "\e[34mBlue Text\e[0m\n"
7. Using tput
(More Readable)
The tput
command abstracts ANSI codes for better readability:
echo "$(tput setaf 1)Red Text$(tput sgr0)"
tput setaf <n>
: Set foreground color (0-7).tput setab <n>
: Set background color (0-7).tput sgr0
: Reset styles.
Examples
- Red bold text:
echo -e "\e[1;31mError!\e[0m"
- Yellow text on blue background:
echo -e "\e[33;44mWarning!\e[0m"
- Underlined green text:
echo -e "\e[4;32mSuccess!\e[0m"
Notes
- Always include
\e[0m
to reset formatting. - Not all terminals support all styles (e.g., blinking may be disabled).
- For 256-color support, use codes like
\e[38;5;<n>m
(replace<n>
with 0-255).
This method works in most Linux terminals (e.g., GNOME Terminal, Konsole).