【问题标题】:coloring in heredocs, bash在 heredocs 中着色,bash
【发布时间】:2014-09-02 06:51:06
【问题描述】:

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

txtred='\e[1;31m'

我将如何在 heredoc 中使用它:

    cat << EOM

    [colorcode here] USAGE:

EOM

我的意思是我应该写什么来代替 [colorcode here] 来呈现这个用法 文字红色? ${txtred} 不起作用,因为这是我在整个过程中使用的 heredoc

之外的 bash 脚本

【问题讨论】:

    标签: bash colors heredoc


    【解决方案1】:

    你需要一些东西来解释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 时,它现在没有。这是因为空间我需要在$trUSAGE 之间插入。
    • 这是一个很好的答案!虽然,我用echo 替换了tput,因为我找不到用于重置的tput 命令。所以txtred=$(echo "\e[1;31m")reset=$(echo "\e[0m")。虽然,如果你真的很喜欢tput,我想this will be really helpful
    【解决方案2】:

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

    txtred='\e[1;31m'
    
    echo -e "$(
    cat << EOM
    ${txtred} USAGE:
    EOM
    )" # this must not be on the EOM line
    

    注意:结束 )" 必须换行,否则会破坏 heredoc 结束标记。

    如果您有很多颜色要使用并且不希望有很多子shell 来设置每个颜色,或者您已经在某个地方定义了转义码并且不想重新发明轮子。

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 2014-06-05
      • 2015-10-17
      • 2014-06-04
      • 2017-04-20
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 2019-11-27
      相关资源
      最近更新 更多