Color text in terminal applications in UNIX [duplicate] Color text in terminal applications in UNIX [duplicate] unix unix

Color text in terminal applications in UNIX [duplicate]


This is a little C program that illustrates how you could use color codes:

#include <stdio.h>#define KNRM  "\x1B[0m"#define KRED  "\x1B[31m"#define KGRN  "\x1B[32m"#define KYEL  "\x1B[33m"#define KBLU  "\x1B[34m"#define KMAG  "\x1B[35m"#define KCYN  "\x1B[36m"#define KWHT  "\x1B[37m"int main(){    printf("%sred\n", KRED);    printf("%sgreen\n", KGRN);    printf("%syellow\n", KYEL);    printf("%sblue\n", KBLU);    printf("%smagenta\n", KMAG);    printf("%scyan\n", KCYN);    printf("%swhite\n", KWHT);    printf("%snormal\n", KNRM);    return 0;}


Different solution that I find more elegant

Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s and a RESET color to end the coloration.

#include <stdio.h>#define RED   "\x1B[31m"#define GRN   "\x1B[32m"#define YEL   "\x1B[33m"#define BLU   "\x1B[34m"#define MAG   "\x1B[35m"#define CYN   "\x1B[36m"#define WHT   "\x1B[37m"#define RESET "\x1B[0m"int main() {  printf(RED "red\n"     RESET);  printf(GRN "green\n"   RESET);  printf(YEL "yellow\n"  RESET);  printf(BLU "blue\n"    RESET);  printf(MAG "magenta\n" RESET);  printf(CYN "cyan\n"    RESET);  printf(WHT "white\n"   RESET);  return 0;}

This program gives the following output:

enter image description here


Simple example with multiple colors

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");

This line produces the following output:

execution's output


You probably want ANSI color codes. Most *nix terminals support them.