Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coloring in heredocs, bash

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

like image 653
branquito Avatar asked Jul 11 '14 15:07

branquito


2 Answers

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
like image 51
Etan Reisner Avatar answered Sep 21 '22 07:09

Etan Reisner


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.

like image 43
bxm Avatar answered Sep 22 '22 07:09

bxm