How to use colors in the terminal (page 2)

botond published 2018. 07. 30., h - 22:14 time

Content

 

Az previous page we've put in some practices to make the terminal more colorful, but there are a few other things to try.

 

 

Use colors in the output of our scripts!

When automating your tasks with scripts, you should consider displaying different output states in different colors. For example, if something has been successfully done in the process, it will be highlighted in green, and if you need to display error messages, it will be highlighted in red.

With this simple example, I illustrate how to accomplish this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/bin/bash
 
# Terminál színek módosítása és visszaállítása ANSI/VT100 escape szekvenciákkal
 
zold1=$(echo -e "\e[00;32m")                    # Zöld kiemelőszín (1. módszer)
zold2=$(echo -e "\033[00;32m")                  # Zöld kiemelőszín (2. módszer)
zold3=$(echo -e "\x1B[00;32m")                  # Zöld kiemelőszín (3. módszer)
 
piros1=$(echo -e "\e[00;31m")                   # Piros kiemelőszín (1. módszer)
piros2=$(echo -e "\033[00;31m")                 # Piros kiemelőszín (2. módszer)
piros3=$(echo -e "\x1B[00;31m")                 # Piros kiemelőszín (3. módszer)
 
reset1=$(echo -e "\e[0m")                       # Színek reset-elése (1. módszer)
reset2=$(echo -e "\033[0m")                     # Színek reset-elése (2. módszer)
reset3=$(echo -e "\x1B[0m")                     # Színek reset-elése (3. módszer)
 
# Terminál színek módosítása és visszaállítása a setaf programmal
 
zold4=$(tput setaf 2)                           # Zöld kiemelőszín (4. módszer)
 
piros4=$(tput setaf 1)                          # Piros kiemelőszín (4. módszer)
 
reset4=$(tput sgr0)                             # Színek reset-elése (4. módszer)
 
# Megjelenítések
 
echo "${zold1}Zöld szín ${reset1} visszaállítva (\e ANSI szekvenciával)"
echo "${zold2}Zöld szín ${reset2} visszaállítva (\033 ANSI szekvenciával)"
echo "${zold3}Zöld szín ${reset3} visszaállítva (\x1B ANSI szekvenciával)"
echo "${zold4}Zöld szín ${reset4} visszaállítva (tput paranccsal)"
 
echo "${piros1}Piros szín ${reset1} visszaállítva (\e ANSI szekvenciával)"
echo "${piros2}Piros szín ${reset2} visszaállítva (\033 ANSI szekvenciával)"
echo "${piros3}Piros szín ${reset3} visszaállítva (\x1B ANSI szekvenciával)"
echo "${piros4}Piros szín ${reset4} visszaállítva (tput paranccsal)"
 
# A színes részek után mindig reseteljük a színeket.

The output of the script is:

Use Colors in the Terminal - Use Colors in Scripts

In this example, we can see that there are several ways to specify the color combination for the terminal. For the first three methods ANSI / VT100 escape sequences were applied before the part to be colored and then reset to default with the reset pre-sequences. The fourth method is the tput program we changed the color attributes. The tput program is specifically used to read or modify various attributes of a terminal, such as color management, querying the row / column size of a terminal, or querying or modifying the cursor position. The principle of operation of the program is similar: Based on the obtained parameters, it produces the appropriate escape sequences on its output instead of us, so we do not have to stuff them.

The principle of operation of each color modification solution is the same: In a sub-shell, we run a command, the output of which is put into a variable. For the first three, this is the echo command, while for the fourth method, it is tput. In each case, the value stored in the variable is an escape sequence for modifying the color attribute. With the first three echo solutions, we could even apply these parts of the control character between quotation marks when writing to the output, but then we would always have to use the -e switch, and the code would not be easy to read.

Thus, we can use these methods to color our scripts so that, for example, in commonly used automation tasks, we can clearly highlight the important parts of the output.

The color codes, as I promised earlier, are listed in the last chapter.

 

Adjust the terminal colors!

If you are already using colors in the terminal routinely, you should check to see if the terminal you are using has the ability to calibrate the colors. For example, if a color is not found to be bright enough to attract attention, we can fix it in the terminal settings.

Since Putty is the most common terminal program, let's look at its configuration now. When you start the program, click on in the small main window Window Kategória C submenu, where you will find many options:

Using Colors in the Terminal - Putty Color Settings

Here we select one of the colors we want to change and then click on the Modify button to bring up the color selection window:

Using Colors in the Terminal - Putty Color Settings - Selecting a Color

Here we set the color that suits us and then chop it.

This allows you to fine tune the colors of the terminal to achieve the desired color scheme. Of course, this change will only apply to us. Also, it's worth keeping in mind that as many terminal programs as there are so many color palettes, so for example, what we have in navy blue will look different in other shades of blue.

 

 

Operation of ANSI / VT100 escape sequences

As mentioned earlier, there are several ways to instruct the terminal to change the color of the next character to be printed. Either use different escape sequences (control characters) before the part to be written, or call the tput program, which sends the appropriate control characters to the terminal instead.

A Bash supports three types of escape sequences:

  • \e
  • \ 033
  • \ x1B

They work exactly the same here, so we'll use the first one to avoid confusion.

There are several ways to use these control characters:

If you enter only one code, it looks like "\ e [xxm "- where xx can also denote the color code or background color code or the attribute code. Example:

echo -e "\e[31mPiros"

In this example, the color code is 31, so it is red. So "\ e [31m "is already printed in red.

Or, if you enter a two-member code, then "\ e [aa;xxm ". Here, too, it can be any of the attribute code, or a color code, or a background color. A semicolon separates the two codes. Attributes indicate different states, such as flickering, brighter state, underlined state, bold, etc. Example:

echo -e "\e[04;31mPiros"

In this example, the red color code is preceded by an 04 attribute code, which represents the underscore. Thus, the "Red" string will appear with underlined red characters.

And you can use three-member code, for example:

echo -e "\e[04;31;44mPiros"

Here is a blue background with 44 code. Thus, "Red" will appear with red underlined text and a blue background.

By copying it to a terminal, we can easily check and try their operation.

So these are the ANSI / VT100 escape sequences. For ease of use, these sequences are stored separately (from the parts after them) in variables that are now much easier to use. See script script above.

 

Tables of color codes and attributes

attributes

Code Operation
0 Delete attributes
1 Bold
2 Pale *
3 Standout *
4 Underline
5 blinking
7 inverted
8 Invisible *

The attributes marked with * did not work on any of my terminals.

Character colors

The following table shows the terminal color codes for the 16 color.

Code Color
39 Default color
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 Light gray
90 Dark gray
91 Light red
92 Light green
93 Light yellow
94 Light blue
95 Light magenta
96 Clear cyan
97 White

Background colors

The following table shows the terminal color codes for the 16 color.

Code Color
49 Default color
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 Light gray
100 Dark gray
101 Light red
102 Light green
103 Light yellow
104 Light blue
105 Light magenta
106 Clear cyan
107 White

example Programs

 

 

In the first example program, we list the character colors and the background colors in two cycles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
 
# Karakterszínek és háttérszínek megjelenítése 16 színű terminál színekkel
 
alahuzas=$(echo -e "\e[04m")    # aláhúzás szekvenciája
alap=$(echo -e "\e[0m")         # reset szekvenciája
 
echo "${alahuzas}Karakter színek:${alap}"
for szinkod in 39 {30..37} {90..97} ; do
    [[ $szinkod = 30 ]] &&  szinkod=$szinkod";107"
    echo -e "\e[${szinkod}mKarakterszín kódja: ${szinkod}${alap}"
done
 
echo
 
echo "${alahuzas}Háttér színek:${alap}"
for hatterkod in 49 {40..47} {100..107} ; do
    echo -e "\e[${hatterkod}m     \e[0m Háttérszín kódja: ${hatterkod}${alap}"
done
 
exit 0

And the output is:

 

Using Colors in the Terminal - 16 Color Program

At the beginning of the program, it loads the underline and reset sequences into two variables, and uses them below to make the code clearer. A condition was added in the first loop that adds a background color of 30 (white) to the color attribute for color code 107 (black) so that the black character color can be seen on it. In the second cycle, it prints 5 space characters with the current background color, then resets the character attributes, and then prints the color codes with the base color.

In the following example program, we interestingly display the 256-color palette with the codes for the character colors and background colors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
 
# Karakterszínek és háttérszínek megjelenítése 256 színű terminál színekkel
 
alahuzas=$(echo -e "\e[04m")    # aláhúzás szekvenciája
alap=$(echo -e "\e[0m")         # reset szekvenciája
karakterszin_mod=38             # 256 színű üzemmód karakterszín módja
                                # 3 tagú szekvenciája: "\e[38;5;Xm" Ahol az X a színkód (0-255)
                                
hatterszin_mod=48               # 256 színű üzemmód háttérszín módja
                                # 3 tagú szekvenciája: "\e[48;5;Xm" Ahol az X a színkód (0-255)
                                
oszlopok_szama=15               # Soronként megjelenítendő oszlopok száma
 
echo "${alahuzas}Karakter színek:${alap}"
 
for szin in {0..255} ; do
    printf "\e[${karakterszin_mod};5;%sm  %3s  \e[0m" $szin $szin   # tabulálás printf-el
    [ $((($szin + 1) % $oszlopok_szama)) == 0 ] && echo             # maradékos osztással törjük a sorokat.
done
 
echo
 
echo "${alahuzas}Háttér színek:${alap}"
 
for szin in {0..255} ; do
    printf "\e[${hatterszin_mod};5;%sm  %3s  \e[0m" $szin $szin     # tabulálás printf-el
    [ $((($szin + 1) % $oszlopok_szama)) == 0 ] && echo             # maradékos osztással törjük a sorokat.
done
 
echo
 
exit 0

The output of this is:

Using Colors in the Terminal - 256 Color Program

In the example program I have tried to make as many parameters as possible variable so that everything is easier to interpret.

As we can see, the terminals can handle even 256 colors. The 256 color management is done by writing a three-membered ANSI code sequence to the output which, when changing character color, is 38; 5; X. Where X represents the color code between 0 and 255. When changing the background color, 48; 5; X is the sequence, here again X is the color code. Let's also see an example:

echo -e "\e[38;5;128mLila \e[38;5;46mÉlénk zöld \e[38;5;208mNarancssárga"

And the same colors with background colors:

echo -e "\e[48;5;128mLila \e[48;5;46mÉlénk zöld \e[48;5;208mNarancssárga"

Of course, here you have to put a black character color (30) in front of it so that the captions are visible, and we also put a reset (0) at the end so that no streaks remain in the terminal:

 echo -e "\e[30m \e[48;5;128mLila \e[48;5;46mÉlénk zöld \e[48;5;208mNarancssárga \e[0m reset"

By running these lines in a terminal, you can experiment with colors using the palette above.

It can be seen here that these sequences can be linked sequentially so that any color / attribute combination can be constructed.

 

 

Conclusion

Thus, these practices have eliminated terminal color management, which can make working in the terminal more comfortable, and these color highlights are also great for raising awareness, for example, if something goes wrong with one of our scripts, we can see the problem sooner.

 

 

Navigation

This description consists of several pages: