在heredocs中着色,bash

问题描述 投票:3回答:1

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

txtred='\e[1;31m'

我如何在heredoc中使用它:

    cat << EOM

    [colorcode here] USAGE:

EOM

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

bash colors heredoc
1个回答
8
投票

你需要一些东西来解释cat不会做的转义序列。这就是为什么你需要echo -e而不仅仅是echo才能使它正常工作。

cat << EOM
$(echo -e "${txtred} USAGE:")
EOM

作品

但你也不能通过使用textred=$(tput setaf 1)来使用转义序列,然后直接使用变量。

textred=$(tput setaf 1)

cat <<EOM
${textred}USAGE:
EOM
© www.soinside.com 2019 - 2024. All rights reserved.