How to Use Colors in Bash Output for Clear Terminal Messages
To use colors in bash output, include ANSI escape codes inside
echo or printf commands. Wrap your text with \e[COLOR_CODEm to start the color and \e[0m to reset it, for example, \e[31mRed Text\e[0m prints red text.Syntax
Colors in bash are created using ANSI escape codes. The general pattern is:
\e[or\033[: starts the escape sequence.COLOR_CODEm: sets the text color or style.- Text to color: the actual output text.
\e[0m: resets the color back to default.
Example: \e[31mRed Text\e[0m prints "Red Text" in red.
bash
echo -e "\e[31mThis is red text\e[0m"Output
This is red text
Example
This example shows how to print text in different colors using bash. It uses echo -e to enable interpretation of escape sequences.
bash
#!/bin/bash echo -e "\e[31mRed\e[0m" echo -e "\e[32mGreen\e[0m" echo -e "\e[33mYellow\e[0m" echo -e "\e[34mBlue\e[0m" echo -e "\e[35mMagenta\e[0m" echo -e "\e[36mCyan\e[0m" echo -e "\e[1;37mBold White\e[0m"
Output
Red
Green
Yellow
Blue
Magenta
Cyan
Bold White
Common Pitfalls
Common mistakes when using colors in bash include:
- Forgetting to use
-ewithecho, so escape codes are not interpreted. - Not resetting color with
\e[0m, causing all following text to stay colored. - Using incorrect or unsupported color codes.
- Using
\033vs\einconsistently (both work but be consistent).
Always test your scripts in the terminal to verify colors show correctly.
bash
echo "\e[31mThis will not be red" echo -e "\e[31mThis will be red\e[0m"
Output
This will not be red
This will be red
Quick Reference
| Color | Code | Description |
|---|---|---|
| Black | 30 | Black text |
| Red | 31 | Red text |
| Green | 32 | Green text |
| Yellow | 33 | Yellow text |
| Blue | 34 | Blue text |
| Magenta | 35 | Magenta text |
| Cyan | 36 | Cyan text |
| White | 37 | White text |
| Bold | 1 | Bold style |
| Reset | 0 | Reset all styles |
Key Takeaways
Use ANSI escape codes with \e[COLOR_CODEm and \e[0m to add colors in bash output.
Always include -e with echo to enable escape sequence interpretation.
Reset colors after colored text to avoid affecting later output.
Test your color codes in the terminal to ensure compatibility.
Use the quick reference table to pick correct color codes easily.