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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With