How to change the output color of echo in Linux?

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

CodeColorExample
30Blackecho -e "\e[30mBlack Text\e[0m"
31Redecho -e "\e[31mRed Text\e[0m"
32Greenecho -e "\e[32mGreen Text\e[0m"
33Yellowecho -e "\e[33mYellow Text\e[0m"
34Blueecho -e "\e[34mBlue Text\e[0m"
35Magentaecho -e "\e[35mMagenta Text\e[0m"
36Cyanecho -e "\e[36mCyan Text\e[0m"
37Whiteecho -e "\e[37mWhite Text\e[0m"

3. Background Color Codes

CodeBackground ColorExample
40Blackecho -e "\e[44;37mBlue BG, White Text\e[0m"
41Redecho -e "\e[41mRed Background\e[0m"
42Greenecho -e "\e[42mGreen Background\e[0m"
43Yellowecho -e "\e[43mYellow Background\e[0m"
44Blueecho -e "\e[44mBlue Background\e[0m"
45Magentaecho -e "\e[45mMagenta Background\e[0m"
46Cyanecho -e "\e[46mCyan Background\e[0m"
47Whiteecho -e "\e[47mWhite Background\e[0m"

4. Text Style Codes

CodeStyleExample
1Boldecho -e "\e[1mBold Text\e[0m"
2Dimecho -e "\e[2mDim Text\e[0m"
4Underlineecho -e "\e[4mUnderlined\e[0m"
5Blinkecho -e "\e[5mBlinking\e[0m"
7Invertecho -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

  1. Red bold text:
   echo -e "\e[1;31mError!\e[0m"
  1. Yellow text on blue background:
   echo -e "\e[33;44mWarning!\e[0m"
  1. 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).

Leave a Reply

Your email address will not be published. Required fields are marked *