Get the App
SLTechnology News&Howtos  ›  Servers  › 

Example of bash shell script displaying text information using ASCII colors

Shulou Source: shulou.com Published: 2022-06-03 05:58:58 09月21日 Update

In bash shell scripts, we can use ASCII colors to display text information.

Format:\ 033\ [31m hello\ 033 [0m

# # m:

Left #: this # can be 3 or 4, but the effect is different.

3: foreground color

4: background color

Right #: color category

1,2,3,4,5,6,7

Use both foreground and background:\ 033 [# #; # # m hello\ 033 [0m]

# m:

Bold, flashing and other functions.

A variety of control characters can be combined and separated by semicolons.

Demo:

Demo background color

Foreground and background are used at the same time

Thickening and flashing function

Actual combat exercise:

Add color to the PS1 variable of your Linux, such as:

1. First of all, we need to add a value to the color part of our PS1.

Export PS1=' [\ 033 [31m\ u\ 033 [0m @\ 033 [32m\ h\ 033 [0m\ 033 [35m\ W\ 033 [0m]\ $'

This setting is really good, meet our needs, but he has a problem, for example, when you enter a very long string, you will find that bash can not automatically wrap the display, but cover the beginning of the same line, slowly back to cover the initial input, this is not optimistic, otherwise when we enter too long content, display content is a problem how to do?

The preliminary judgment is that the color code is added to the problem, which may be that in the PS1 environment variable, the color code is not suitable to be added directly to the PS1, so we need to correct it by adding\ [and\] after each color code.

For example:

Export PS1=' [\ [\ 033 [31m\]\ u\ [\ 033 [0m\] @\ [\ 033 [32m\]\ h\ [\ 033 [0m\]\ [\ 033 [35m\]\ W\ [\ 033 [0m\]]\ $'

You can see how many color codes need to be added\ [and]. Once this is set up, the problem will be eliminated, and we can continue to happily enter long commands on the terminal.

Tags: Color code background input content question foreground function variable and at the same time appearance part presentation message text script good happy optimistic Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Apple OPPO Reno Xiaomi Shulou Technology