coloring in heredocs, bash

◇◆丶佛笑我妖孽 提交于 2021-02-05 06:21:11

问题


If I have previously defined color variable like this:

txtred='\e[1;31m'

How would I use it in heredoc:

    cat << EOM

    [colorcode here] USAGE:

EOM

I mean what should I write in place of [colorcode here] to render that USAGE text red? ${txtred} won't work, as that is what I am using throughout my bash script, outside of heredoc


回答1:


You need something to interpret the escape sequence which cat won't do. This is why you need echo -e instead of just echo to make it work normally.

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

works

but you could also not use escape sequences by using textred=$(tput setaf 1) and then just use the variable directly.

textred=$(tput setaf 1)

cat <<EOM
${textred}USAGE:
EOM



回答2:


Late to the party, but another solution is to echo -e the entire heredoc block via command substitution:

txtred='\e[1;31m'

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

NB: the closing )" must fall on a new line, or it'll break the heredoc end marker.

This option might be appropriate if you have a lot of colours to use and don't want a lot of subshells to set each of them up, or you already have your escape codes defined somewhere and don't want to reinvent the wheel.



来源:https://stackoverflow.com/questions/24701227/coloring-in-heredocs-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!