How to change the output color of echo in Linux

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

    A neat way to change color only for one echo is to define such function:

    function coloredEcho(){
        local exp=$1;
        local color=$2;
        if ! [[ $color =~ '^[0-9]$' ]] ; then
           case $(echo $color | tr '[:upper:]' '[:lower:]') in
            black) color=0 ;;
            red) color=1 ;;
            green) color=2 ;;
            yellow) color=3 ;;
            blue) color=4 ;;
            magenta) color=5 ;;
            cyan) color=6 ;;
            white|*) color=7 ;; # white or invalid color
           esac
        fi
        tput setaf $color;
        echo $exp;
        tput sgr0;
    }
    

    Usage:

    coloredEcho "This text is green" green
    

    Or you could directly use color codes mentioned in Drew's answer:

    coloredEcho "This text is green" 2
    

提交回复
热议问题