I have multiple Bash variables for ANSI terminal colors. One is ANSI_NOCOLOR
and defined as this:
ANSI_NOCOLOR="\e[0m"
When I use it togather with a backslash character \
(escaped as \\
in Bash strings), I get an unexpected output.
Example:
echo -e "command --with --many --options \\$ANSI_NOCOLOR"
echo -e "--more --options"
This results in:
command --with --many --options \e[0m
--more --options
This example can be reduced to:
$ echo -e "\\\e[0m"
\e[0m
Why is a tripple backslash in Bash not acting as normally known from other C-like languages?
Expected / C-like behavior:
Escape sequences are left-associative. Thus,
- the first two
\\
are printed as\
, - the remaining
\
is doing a look-ahead(1) to finde
for creating theESC
character.
Workaround:
After some planing with backslashes, I found, that 5 !! backslashes are required. I still would like to read an explanation, why it behaves as it is.
$ echo -e "\\\\\e[33mfoo\e[0m"
\foo
It's hard to control a color-reset sequence, so my workaround uses two ANSI color escape sequences, to set it to yellow and back to default.