我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。我该怎么做?
我正在尝试使用echo命令在终端中打印文本。
我想用红色打印文本。我该怎么做?
当前回答
我应该使用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
其他回答
我应该使用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
这是我过去看到的所有组合,并决定哪一个读起来很酷:
for (( i = 0; i < 8; i++ )); do
for (( j = 0; j < 8; j++ )); do
printf "$(tput setab $i)$(tput setaf $j)(b=$i, f=$j)$(tput sgr0)\n"
done
done
red='\e[0;31m'
NC='\e[0m' # No Color
echo -e "${red}Hello Stackoverflow${NC}"
这个答案是正确的,只是对颜色的调用不应该在引号内。
echo -e ${red}"Hello Stackoverflow"${NC}
应该会成功的。
以下是我最终使用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'"/"
打印方式如下:
echo -e "\033[31m Hello World"
[31m控制文本颜色:
30-37套前景色40-47套背景色
这里可以找到更完整的颜色代码列表。
最好将字符串末尾的文本颜色重置回\033[0m。