How to change the output color of echo in Linux

后端 未结 29 4047
刺人心
刺人心 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 05:08

    This question has been answered over and over again :-) but why not.

    First using tput is more portable in modern environments than manually injecting ASCII codes through echo -E

    Here's a quick bash function:

     say() {
         echo "$@" | sed \
                 -e "s/\(\(@\(red\|green\|yellow\|blue\|magenta\|cyan\|white\|reset\|b\|u\)\)\+\)[[]\{2\}\(.*\)[]]\{2\}/\1\4@reset/g" \
                 -e "s/@red/$(tput setaf 1)/g" \
                 -e "s/@green/$(tput setaf 2)/g" \
                 -e "s/@yellow/$(tput setaf 3)/g" \
                 -e "s/@blue/$(tput setaf 4)/g" \
                 -e "s/@magenta/$(tput setaf 5)/g" \
                 -e "s/@cyan/$(tput setaf 6)/g" \
                 -e "s/@white/$(tput setaf 7)/g" \
                 -e "s/@reset/$(tput sgr0)/g" \
                 -e "s/@b/$(tput bold)/g" \
                 -e "s/@u/$(tput sgr 0 1)/g"
      }
    

    Now you can use:

     say @b@green[[Success]] 
    

    to get:

    Notes on portability of tput

    First time tput(1) source code was uploaded in September 1986

    tput(1) has been available in X/Open curses semantics in 1990s (1997 standard has the semantics mentioned below).

    So, it's (quite) ubiquitous.

提交回复
热议问题