Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color in OS X console output

I'm trying to change the output of an console application, but I'm finding just Windows versions of the code, which of course don't work in OS X.

The code should look like following:

printf("some text"); //this should be in green

I know, this is only a printf() execution, but how can I convert the output color?

like image 540
Dominic Järmann Avatar asked Oct 23 '15 18:10

Dominic Järmann


1 Answers

The Terminal application on Mac OS X responds to the standard ANSI escape codes for colors when they are printed using, for example, printf() in C/C++ or std::cout << in C++.

The strings that can be used to set foreground and/or background color look like this:

To set only the foreground color:

 "\x1b[30m"

To set only the background color:

 "\x1b[40m"

To set foreground and background color:

 "\x1b[30;40m"

To reset all color attributes back to normal:

 "\x1b[0m"

In the above strings the numbers 30 and 40 are just placeholders for foreground and background color codes, they can be replaced by the numbers from the table below to get one of 8 standard colors:

+---------+------------+------------+
|  color  | foreground | background |
|         |    code    |    code    |
+---------+------------+------------+
| black   |     30     |     40     |
| red     |     31     |     41     |
| green   |     32     |     42     |
| yellow  |     33     |     43     |
| blue    |     34     |     44     |
| magenta |     35     |     45     |
| cyan    |     36     |     46     |
| white   |     37     |     47     |
+---------+------------+------------+

Here is an example:

printf("\x1b[32m green text on regular background \x1b[0m  \n");
printf("\x1b[32;40m green text on black background \x1b[0m  \n");
printf("\x1b[42m regular text on green background \x1b[0m  \n");

It looks like this on a Mac OS X El Capitan (in a Terminal window which by default has black text on a white background).

enter image description here

like image 120
WhiteViking Avatar answered Nov 15 '22 01:11

WhiteViking