Skip to content

Introduction

When we download bash scripts that have been written by others in our daily work, sometimes some key strings are marked with special colors. How can this effect be achieved by writing in a script?

Font color

color codedescription
30black
31red
32green
33yellow
34blue
35purple
36dark green
37white

Background color of font

background color codedescription
40black
41crimson
42green
43yellow
44blue
45purple
46dark green
47white

Display mode

codedescription
0Terminal default settings
1Highlight
4Underline
5Cursor blinks
7Reverse display
8Hide

Mode of execution

  • \033[1;31;40m "1" indicates the display mode, which is optional. "31" indicates the font color. "40m" indicates the font background color

  • \033[0m Restore the terminal default color, that is, cancel the color setting

Script example

We can write a script to observe the color change.

#!/bin/bash
# Font color cycle
for color1 in {31..37}
    do
        echo -e "\033[0;${color1};40m---hello! world---\033[0m"
    done

echo "-------"

# Background color cycle
for color2 in {40..47}
    do
        echo -e "\033[30;${color2}m---hello! world---\033[0m"
    done

echo "-------"

# Cycle of display mode
for color3 in 0 1 4 5 7 8
    do
        echo -e "\033[${color3};37;40m---hello! world---\033[0m"
    done
Shell > chmod a+x color_set.sh
Shell > ./color_set.sh

The effect is as follows:

image1

Author: tianci li

Contributors: Steven Spencer