Parsing the text that sets colors in a bash shell

255 views Asked by At

Could someone either point me to some documentation on the web that would explain how a bash shell would pars the following lines that sets up colors or explain from the parsers view, how the following lines would be read?

  • I know that 32 cause dark green to be displayed
  • 34 causes dark blue to be displaied

but what is the first \033 used for and what dose the 'm' after the 32 and 33 do?

green ="\[\033[0;32m\]"
blue="\[\033[0;34m\]" 

and eventually export these and other items to PS1

1

There are 1 answers

1
Thomas Dickey On BEST ANSWER

The best place to start reading for bash is the Bash Prompt HOWTO, specifically the section Bash Prompt Escape Sequences.

The characters \033 (called esc or escape) followed by a left square bracket [ is the way 7-bit characters form the ECMA-48 control sequence initiator (CSI). That starts a control sequence, which continues until the final character (has to be from the range 64-126) which in this case is m. The final character is one of the things that determines what type of control sequence it is — this one is the SGR (set graphic rendition).

While most final characters are alphabetic (A-Z or a-z), a few are not. XTerm Control Sequences lists some for instance:

CSI Pm `  Character Position Absolute  [column] (default = [row,1])
          (HPA).
CSI Pt; Pl; Pb; Pr $ {
          Selective Erase Rectangular Area (DECSERA), VT400 and up.
            Pt; Pl; Pb; Pr denotes the rectangle.
CSI Ps ' |
          Request Locator Position (DECRQLP).
CSI Pm ' }
          Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.
CSI Pm ' ~
          Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.

For your example

green ="\[\033[0;32m\]"

Taking it apart:

  • The \[ and \] tell bash to discount the enclosed characters (do not count them as printable characters with a width). This is bash-specific. If you used zsh, there is a different way to do the same thing. Most shells (such as ksh) do not provide this feature.
  • The 0 in the SGR sequence resets any attribute (such as color) which an SGR sequence might have set.
  • The ; semicolon separates that from the next parameter, which is a particular color.
  • ECMA-48 defines 8 foreground and 8 background colors (often referred to as "ANSI colors" although it has been a long time since there was a corresponding ANSI standard).