在heredocs中着色,bash

bra*_*ito 3 bash colors heredoc

如果我之前已经定义了这样的颜色变量:

txtred='\e[1;31m'
Run Code Online (Sandbox Code Playgroud)

我如何在heredoc中使用它:

    cat << EOM

    [colorcode here] USAGE:

EOM
Run Code Online (Sandbox Code Playgroud)

我的意思是我应该写什么代替[colorcode here]将USAGE文本呈现为红色?${txtred}不会起作用,因为这是我在整个bash脚本中使用的,在heredoc之外

bxm*_*bxm 11

迟到了,但另一个解决方案是通过命令替换echo -e整个heredoc块:

txtred='\e[1;31m'

echo -e "$(
cat << EOM
${txtred} USAGE:
EOM
)" # this must not be on the EOM line
Run Code Online (Sandbox Code Playgroud)

注意:收盘价)"必须落在新的一行上,否则会破坏heredoc结束标记。

如果您有很多颜色可供使用并且不希望使用大量子 shell 来设置每个颜色,或者您已经在某处定义了转义码并且不想重新发明轮子,则此选项可能是合适的。


Eta*_*ner 8

你需要一些东西来解释逃避序列,这是cat不会做的.这就是为什么你需要echo -e而不仅仅是echo让它正常工作.

cat << EOM
$(echo -e "${txtred} USAGE:")
EOM
Run Code Online (Sandbox Code Playgroud)

作品

但你也可以不使用转义序列textred=$(tput setaf 1),然后直接使用变量.

textred=$(tput setaf 1)

cat <<EOM
${textred}USAGE:
EOM
Run Code Online (Sandbox Code Playgroud)