views:

305

answers:

3

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

+2  A: 

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.

Carl Norum
Assuming ANSI escape sequences, as popularized by VT100 derivatives (VT1xx didn't have color). And you could have used `"\033"` instead of `"%c", 27`.
ephemient
@ephemient, even `\e` worked on my machine. OS X's terminal and most linux console apps support the ANSI escape sequences, so I think it satisfies his question.
Carl Norum
+1  A: 

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.

ephemient
A: 

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).

lugte098