I'm printing a message in a Bash script, and I want to colourise a portion of it; for example,
#!/bin/bash
normal='\e[0m'
yellow='\e[33m'
cat <<- EOF
${yellow}Warning:${normal} This script repo is currently located in:
[ more messages... ]
EOF
But when I run in the terminal (tmux
inside gnome-terminal
) the ANSI escape characters are just printed in \
form; for example,
\e[33mWarning\e[0m This scr....
If I move the portion I want to colourise into a printf
command outside the here-doc, it works. For example, this works:
printf "${yellow}Warning:${normal}"
cat <<- EOF
This script repo is currently located in:
[ more messages... ]
EOF
From man bash
– Here Documents:
No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and
\
must be used to quote the characters\
,$
, and`
.
I can't work out how this would affect ANSI escape codes. Is it possible to use ANSI escape codes in a Bash here document that is cat
ted out?
\e[33m
and is substituted normally in both cases. If you have some reason to think it's confined to heredocs, or a bit of real code that shows the behaviour you're interested in, please edit it in.yellow=$'\e[33m'
oryellow=$(printf '\e[33m')
(as you're already doing) will put the escape character into the string directly to test with.'\e[33m'
is meaningless to a terminal? it only has meaning to commands likeecho -e
orprintf
- which then produce the "real" code that gets sent to the terminal?