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

前端 未结 3 1016
终归单人心
终归单人心 2020-12-04 15:32

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

相关标签:
3条回答
  • 2020-12-04 16:16

    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.

    0 讨论(0)
  • 2020-12-04 16:17

    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.

    0 讨论(0)
  • 2020-12-04 16:25

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

    0 讨论(0)
提交回复
热议问题