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

前端 未结 3 1025
终归单人心
终归单人心 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.

提交回复
热议问题