9

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

branquito
  • 3,864
  • 5
  • 35
  • 60

2 Answers2

12

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
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Great. Is there a way to preserve formatting, because right know as it is, it moves `USAGE` text to the right? – branquito Jul 11 '14 at 15:35
  • Sorry it does not now, when I use `${tr}` instead of `$tr`. It was because of space I needed to insert beetween `$tr` and `USAGE`. – branquito Jul 11 '14 at 15:36
  • This is a great answer! Although, I replaced `tput` with `echo` because I couldn't find a `tput` command for reset. so `txtred=$(echo "\e[1;31m")` and `reset=$(echo "\e[0m")`. Although, if you're really into `tput` I think [this will be really helpful](https://unix.stackexchange.com/questions/269077/tput-setaf-color-table-how-to-determine-color-codes) – Justin Wrobel Aug 03 '21 at 15:17
10

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.

bxm
  • 484
  • 4
  • 10