Home » Linux » How can I print to the console in color in a cross-platform manner?

How can I print to the console in color in a cross-platform manner?

Posted by: admin November 30, 2017 Leave a comment

Questions:

How can I output colored text using “printf” on both Mac OS X and Linux?

Answers:

You can use the ANSI colour codes. Here’s an example program:

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("%c[1;31mHello, world!\n", 27); // red
  printf("%c[1;32mHello, world!\n", 27); // green
  printf("%c[1;33mHello, world!\n", 27); // yellow
  printf("%c[1;34mHello, world!\n", 27); // blue
  return 0;
}

The 27 is the escape character. You can use \e if you prefer.

There are lists of all the codes all over the web. Here is one.

Questions:
Answers:

Another option is:

# Define some colors first (you can put this in your .bashrc file):
red='\e[0;31m'
RED='\e[1;31m'
blue='\e[0;34m'
BLUE='\e[1;34m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
green='\e[0;32m'
GREEN='\e[1;32m'
yellow='\e[0;33m'
YELLOW='\e[1;33m'
NC='\e[0m'
#################

Then you can type in the terminal:

echo -e "${RED}This is an error${NC}"
echo -e "${YELLOW}This is a warning${NC}"
echo -e "${GREEN}Everythings fine!${NC}"

Do not forget the ${NC} at the end. NC stands for “no color”, which means that after your sentence, it will revert back to normal color. If you forget it, the whole prompt and commands afterwards will be in the color you specified (of course you can type ‘echo -e “${NS}”‘ to change it back).

Questions:
Answers:

For the best portability, query the terminfo database. In shell,

colors=(black red green yellow blue magenta cyan white)
for ((i = 0; i < ${#colors[*]}; i++)); do
    ((j=(i+1)%${#colors[*]}))
    printf '%s%s%s on %s%s\n' "$(tput setaf $i)" "$(tput setab $j)" \
            "${colors[i]}" "${colors[j]}" "$(tput op)"
done

will print out

black on red
red on green
green on yellow
yellow on blue
blue on magenta
magenta on cyan
cyan on white
white on black

but in color.