Rainbow in terminal and one hour is gone

Stumbling upon a rainbow in terminal I desired to learn how it works. Puff! An hour later… 🙂

rainbow in your shell

The trigger

So, it worked and now why / how?


Trick is simple (now):

  1. Terminals have codes
  2. Codes make terminals do things (like set background colours)
  3. To tell terminal you pass it a code, you need to use escape code and then the actual code.
  4. So, here is a simplified example:
simplified terminal rainbow, to make explanation easier


And now how it works:

  1. magic numbers 40-49 are original 8 colours in the terminal + reset
  2. \e is the Escape code
  3. ANSI values of the codes are (almost always) prepended with [, so
  4. [40m sets background colour
  5. and \n is a line-feed, to make printf move to new line and actually mark whole line in the background colour set



the actual script:

  1. yes is a yes-man, outputs given string until killed
  2. seq gives a sequence, 231 230 229 … 16
  3. this sequence is piped to read and printf, which I simplified with for in the simplified script above
  4. \x is for hex in printf
  5. 1b is escape sequence (27 decimal, Escape code)
  6. the reason for a sequence is to use RGB
ESC[ … 38;2;<r>;<g>;<b> … m Select RGB foreground color
ESC[ … 48;2;<r>;<g>;<b> … m Select RGB background color

So, in the end, only one mystery remains, that is 5. It actually tells the terminal I want/have 256 colours. And there you go:

script at work


  1. Terminal codes how they really should be used: http://wiki.bash-hackers.org/scripting/terminalcodes
  2. Wikipedia and colour list: https://en.wikipedia.org/wiki/ANSI_escape_code
  3. Great answer by SiegeX on SO that led me to both links above: https://stackoverflow.com/a/5413029/999165

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s