bash 使用 echo 为一个单词着色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16845699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:33:33  来源:igfitidea点击:

Bash colour one word using echo

bashcolorsecho

提问by Zippyduda

I am wanting to colourize one word in the middle of an echo sentence, but can't seem to achieve this.

我想为回声句子中间的一个词着色,但似乎无法实现这一点。

This works:

这有效:

#!/bin/bash
wipe="3[1m3[0m"
yellow='\E[1;33'
echo -e "$yellow"
echo Hello World
echo -e "$wipe"

But this doesn't:

但这不会:

#!/bin/bash
wipe="3[1m3[0m"
yellow='\E[1;33'
black="40m"
echo -e "Output a $yellow coloured $wipe word."
# or
echo -e "Output a ${yellow} coloured ${wipe} word."

What am I stupidly doing wrong? :)

我愚蠢地做错了什么?:)

采纳答案by Lynn

You forgot an min your ANSI escape code for yellow. This works:

m在 ANSI 转义码中忘记了yellow. 这有效:

yellow='\E[1;33m'

回答by tarrsalah

Much better, use tputto set a foreground colour:

更好的是,使用tput设置前景色:

textreset=$(tput sgr0) # reset the foreground colour
red=$(tput setaf 1)
yellow=$(tput setaf 2) 

echo "Output a ${yellow} coloured ${textreset} ${red} word ${textreset}."