问题
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