To print colored text in the Bash terminal, you use special sequences called ANSI Escape Codes.
In Bash, you use the echo -e command (the -e flag enables the interpretation of backslash escapes) followed by a code that tells the terminal to change color.
The Basic Syntax
The general format is: \033[<COLOR>mYour Text\033[0m
\033[: Starts the escape sequence.<COLOR>: The numeric code for the color.m: Ends the color code.\033[0m: Very important! This is the "Reset" code. It stops the color so that your entire terminal doesn't stay colored forever.
Common Color Codes
| Color | Code |
|---|---|
| Red | 31 |
| Green | 32 |
| Yellow | 33 |
| Blue | 34 |
| Reset | 0 |
Examples
You can try these directly in your terminal or add them to your variables.sh script:
# Print Red text
echo -e "\033[31mThis is Red text\033[0m"
# Print Green text
echo -e "\033[32mThis is Green text\033[0m"
# Print Yellow text
echo -e "\033[33mThis is Yellow text\033[0m"
Using Variables for Colors (Pro Tip)
Since you are learning about variables, it's much easier to store colors in variables so your code stays readable:
#!/bin/bash
RED='\033[31m'
GREEN='\033[32m'
NC='\033[0m' # No Color (Reset)
echo -e "${RED}Error:${NC} Something went wrong!"
echo -e "${GREEN}Success:${NC} The variable is $PRICE_PER_APPLE"
In the example above, ${NC} ensures that only the words "Error" or "Success" are colored, and the rest of the line returns to normal.
Give it a try in your terminal! It's a fun way to make your scripts look professional.