我正在尝试使用echo命令在终端中打印文本。

我想用红色打印文本。我该怎么做?


当前回答

只为一个回声改变颜色的一个简单方法是定义这样的函数:

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;
}

用法:

coloredEcho "This text is green" green

或者你可以直接使用德鲁回答中提到的颜色代码:

coloredEcho "This text is green" 2

其他回答

我写了swag就是为了实现这一点。

你可以这样做

pip install swag

现在,您可以通过以下方式将所有转义命令作为txt文件安装到给定目标:

swag install -d <colorsdir>

或者更容易通过:

swag install

这将把颜色安装到~/.colors。

您可以这样使用它们:

echo $(cat ~/.colors/blue.txt) This will be blue

或者这样,我觉得更有趣:

swag print -c red -t underline "I will turn red and be underlined"

在ascinema上查看!

以下是我最终使用sed的结果

echo " [timestamp] production.FATAL Some Message\n" \
"[timestamp] production.ERROR Some Message\n" \
"[timestamp] production.WARNING Some Message\n" \
"[timestamp] production.INFO Some Message\n" \
"[timestamp] production.DEBUG Some Message\n"  | sed \
-e "s/FATAL/"$'\e[31m'"&"$'\e[m'"/" \
-e "s/ERROR/"$'\e[31m'"&"$'\e[m'"/" \
-e "s/WARNING/"$'\e[33m'"&"$'\e[m'"/" \
-e "s/INFO/"$'\e[32m'"&"$'\e[m'"/" \
-e "s/DEBUG/"$'\e[34m'"&"$'\e[m'"/"

打印方式如下:

这个问题已经被一次又一次地回答了:-)但为什么不呢。

首先使用tput在现代环境中比通过echo-E手动注入ASCII代码更容易移植

下面是一个快速的bash函数:

 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"
  }

现在您可以使用:

 say @b@green[[Success]] 

得到:

关于tput可移植性的说明

1986年9月首次上传tput(1)源代码

tput(1)在20世纪90年代已在X/Open curses语义中可用(1997年标准具有以下提到的语义)。

因此,它(相当)无处不在。

如果您使用zsh或bash

black() {
    echo -e "\e[30m${1}\e[0m"
}

red() {
    echo -e "\e[31m${1}\e[0m"
}

green() {
    echo -e "\e[32m${1}\e[0m"
}

yellow() {
    echo -e "\e[33m${1}\e[0m"
}

blue() {
    echo -e "\e[34m${1}\e[0m"
}

magenta() {
    echo -e "\e[35m${1}\e[0m"
}

cyan() {
    echo -e "\e[36m${1}\e[0m"
}

gray() {
    echo -e "\e[90m${1}\e[0m"
}

black 'BLACK'
red 'RED'
green 'GREEN'
yellow 'YELLOW'
blue 'BLUE'
magenta 'MAGENTA'
cyan 'CYAN'
gray 'GRAY'

联机尝试

要显示具有不同颜色的消息输出,可以执行以下操作:

echo -e "\033[31;1mYour Message\033[0m"

-黑色0;30深灰色1;30-红色0;31浅红色1;31-绿色0;32浅绿色1;32-棕色/橙色0;33黄色1;33-蓝色0;34浅蓝色1;34-紫色0;35浅紫色1;35-青色0;36浅青色1;36-浅灰色0;37白色1;37