【发布时间】:2014-09-02 06:51:06
【问题描述】:
如果我之前定义了这样的颜色变量:
txtred='\e[1;31m'
我将如何在 heredoc 中使用它:
cat << EOM
[colorcode here] USAGE:
EOM
我的意思是我应该写什么来代替 [colorcode here] 来呈现这个用法
文字红色? ${txtred} 不起作用,因为这是我在整个过程中使用的
heredoc
【问题讨论】:
如果我之前定义了这样的颜色变量:
txtred='\e[1;31m'
我将如何在 heredoc 中使用它:
cat << EOM
[colorcode here] USAGE:
EOM
我的意思是我应该写什么来代替 [colorcode here] 来呈现这个用法
文字红色? ${txtred} 不起作用,因为这是我在整个过程中使用的
heredoc
【问题讨论】:
你需要一些东西来解释cat 不会做的转义序列。这就是为什么您需要echo -e 而不仅仅是echo 才能使其正常工作的原因。
cat << EOM
$(echo -e "${txtred} USAGE:")
EOM
作品
但您也不能通过使用textred=$(tput setaf 1) 来使用转义序列,然后直接使用变量。
textred=$(tput setaf 1)
cat <<EOM
${textred}USAGE:
EOM
【讨论】:
USAGE 文本向右移动?
${tr} 而不是 $tr 时,它现在没有。这是因为空间我需要在$tr 和USAGE 之间插入。
echo 替换了tput,因为我找不到用于重置的tput 命令。所以txtred=$(echo "\e[1;31m") 和reset=$(echo "\e[0m")。虽然,如果你真的很喜欢tput,我想this will be really helpful
聚会迟到了,但另一个解决方案是通过命令替换echo -e 整个 heredoc 块:
txtred='\e[1;31m'
echo -e "$(
cat << EOM
${txtred} USAGE:
EOM
)" # this must not be on the EOM line
注意:结束 )" 必须换行,否则会破坏 heredoc 结束标记。
如果您有很多颜色要使用并且不希望有很多子shell 来设置每个颜色,或者您已经在某个地方定义了转义码并且不想重新发明轮子。
【讨论】: