Bash Color & Prompt String

Bash Color

In bash, strings can be print with different formats including different front or background colors, blink, bold or hide etc.

Basically you just prepend some format string start with escape character, say <esc> followed by '[', and append a 'm', then you are good to go. (”<esc>[FormatCodem”)


echo -e "\033[31mHello\e[0m World"

\033[ act as escape characters, then '31' means red, and end with an 'm', then followed by a string 'Hello'. So 'Hello' would be printed in red.
Then '\e[' represents escape characters, then '0m' means reset all formats. So 'World' would be printed in white.

escape character

  • \e
  • \033
  • \x1B

For further info, please check this out:
[bash tips - colors and formatting]

Prompt String

Prompt string is like this one.
Prompt string is basically some formatted string using the format code talked above.

where to put the format string?

export it to PS1 environment variables
So you append following line to ~/.bashrc:

export PS1='\[\033[00m\]\[\033[01m\][ \[\033[0;34m\]\u@\h\[\033[0;1m\] ]\[\033[0;34m\]\w\n\[\033[0;1m\]$ '
tricky point

Noticed that there always are '[' and ']' surrounding every format string. Technically it's not necessary.
But the tricky thing is,if you don't use '[ ' and ']' in the new line, say '\n$ ', like the following line, your bash may mess up when you tracing back some history commands.

export PS1='\[\033[00m\]\[\033[01m\][ \[\033[0;34m\]\u@\h\[\033[0;1m\] ]\[\033[0;34m\]\w\n\033[0;1m$ '

so like when I press up up down, the first 5 characters of 'cd practise' would remain there and the start position of new command kind of messed up.

Thus, you need to use '[' and ']' to surround then so that to declare things between are format strings.

Bash Color & Prompt String
Share this