How to change the output color of echo in Linux

后端 未结 29 4050
刺人心
刺人心 2020-11-22 04:28

I am trying to print a text in the terminal using echo command.

I want to print the text in a red color. How can I do that?

29条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 04:52

    I instead of hard coding escape codes that are specific to your current terminal, you should use tput.

    This is my favorite demo script:

    #!/bin/bash
    
    tput init
    
    end=$(( $(tput colors)-1 ))
    w=8
    for c in $(seq 0 $end); do
        eval "$(printf "tput setaf %3s   " "$c")"; echo -n "$_"
        [[ $c -ge $(( w*2 )) ]] && offset=2 || offset=0
        [[ $(((c+offset) % (w-offset))) -eq $(((w-offset)-1)) ]] && echo
    done
    
    tput init
    

提交回复
热议问题