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

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


当前回答

使用tput计算颜色代码。避免使用ANSI转义码(例如,\e[31;1m表示红色),因为它不易移植。例如,OS X上的Bash不支持它。

BLACK=`tput setaf 0`
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
MAGENTA=`tput setaf 5`
CYAN=`tput setaf 6`
WHITE=`tput setaf 7`

BOLD=`tput bold`
RESET=`tput sgr0`

echo -e "hello ${RED}some red text${RESET} world"

其他回答

echo -e "\033[31m Hello World"

[31m控制文本颜色:

30-37套前景色40-47套背景色

这里可以找到更完整的颜色代码列表。

最好将字符串末尾的文本颜色重置回\033[0m。

使用具有setaf功能和参数1的tput。

echo "$(tput setaf 1)Hello, world$(tput sgr0)"

以下是我最终使用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,而不是硬编码特定于当前终端的转义码。

这是我最喜欢的演示脚本:

#!/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

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

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