乐闻世界logo
搜索文章和话题

How to change the output color of echo in Linux

1个答案

1

In Linux, you can change the output color of the echo command by using special ANSI escape sequences. ANSI escape sequences are used to control terminal text display, including color and cursor position. The format is generally:

shell
echo -e "\e[COLOR_CODEmTEXT\e[0m"

Where the -e option allows the echo command to interpret the escape characters included. \e[COLOR_CODEm is used to set the color, and \e[0m is used to reset the color to default. Color codes are specific numeric codes representing different colors. For example:

  • 31 represents red
  • 32 represents green
  • 33 represents yellow
  • 34 represents blue
  • 35 represents purple
  • 36 represents cyan
  • 37 represents white

Example

If you want the output text to be red, you can write:

bash
echo -e "\e[31mThis is red text\e[0m"

This will output the text 'This is red text' in red, and the text color will reset to default afterward.

Practical Example

Suppose you are writing a script and need to warn users about certain operations; you can use red output to increase the visibility of the warning:

bash
echo -e "\e[31mWarning: This operation will delete important files!\e[0m"

This helps ensure that users notice this important warning message.

By doing this, you can use different colors as needed to enhance the readability of scripts and the user experience.

2024年8月14日 17:57 回复

你的答案