How to change the terminal colours from command line or console

So, I have been working on this console based project that prints a lot of messages. I wanted to make certain messages - warning etc. to be highlighted so that it could catch the user's eye easily. Since, the code was in C, I looked for printing colour using printf and came to know about this old school way of changing a terminal colours through commands.

Earlier using escape sequences (because they start with an escape character) people used to manage remote terminals. You can try this out in your own terminal. All we have to do is echo the escape sequence. The syntax is:

[shredder12]$ echo "^[[attr;fg;bgm"

This looks a little complicated but its pretty simple. The first two characters "^[" stand for the escape key. You can get this by pressing "Ctrl + V" followed by pressing the Esc key. Rest of the three are attributes, foreground and background colour respectively.

The following table will give you a better idea of these three parameters

Attributes - attr

  • 0 - Reset All Attributes (return to normal mode)
  • 1 - Bright (Usually turns on BOLD)
  • 2 - Dim
  • 3 - Underline
  • 5 - Blink
  • 7 - Reverse
  • 8 - Hidden

Foreground color - fg

  • 30 - Black
  • 31 - Red
  • 32 - Green
  • 33 - Yellow
  • 34 - Blue
  • 35 - Magenta
  • 36 - Cyan
  • 37 - White

Background color - bg

  • 40 - Black
  • 41 - Red
  • 42 - Green
  • 43 - Yellow
  • 44 - Blue
  • 45 - Magenta
  • 46 - Cyan
  • 47 - White

Change the colour of font(foreground) to Red

So, lets try turning the output into Red

Note that, not specifying the background colour leaves it unchanged.

Once changed, you can easily reset it back. This can be done in a similar way.

0 attr stands for resetting all the attributes to default.

Swap the fg and bg colours

Once again, you can rever back using the attr 0.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <p> <br>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.