I would like to be able to do something like this
VAR='\\'
echo "$VAR"
and get as result
\\
The result that I actually have is
\
Actually, I have a very long string with many \\ and when I print it bash removes the first \ .
I would like to be able to do something like this
VAR='\\'
echo "$VAR"
and get as result
\\
The result that I actually have is
\
Actually, I have a very long string with many \\ and when I print it bash removes the first \ .
For bash
's builtin echo
command to output a given string verbatim followed by a newline character, you need:
# switch from PWB/USG/XPG/SYSV-style of echo to BSD/Unix-V8-style of echo
# where -n/-e options are recognised and backslash sequences not enabled by
# default
shopt -u xpg_echo
Use -n (skip adding a newline) with $'\n' (add a newline by hand) to make
sure the contents of $VAR
is not treated as an option if it starts with -
echo -n "$VAR"$'\n'
Or:
# disable POSIX mode so options are recognised even if xpg_echo is also on:
set +o posix
use -E to disable escape processing, and we use -n (skip adding a newline)
with $'\n' (add a newline by hand) to make sure the contents of $VAR
is not
treated as an option if it starts with -
echo -En "$VAR"$'\n'
Those are specific to the bash
shell, you'd need different approaches for other shells/echo
s, and note that some implementations won't let you output arbitrary strings.
But best here is to use printf
instead which is the standard command for that:
printf '%s\n' "$VAR"
See Why is printf better than echo? for details.
use 4 backslashes instead of 2
bash
shell by default (on most systems) would not output one but two backslashes when running the commands that the user is showing.
– Kusalananda
Jan 22 '21 at 18:34
bash
'secho
to expand backslash sequences by default. In any case, you don't want to useecho
to output arbitrary strings as noted in the Q&A I linked to. – Stéphane Chazelas Jan 22 '21 at 15:12xpg_echo
shell option set in your shell? Or are you actually using-e
withecho
(but forgot to type that in the question)? – Kusalananda Jan 22 '21 at 15:21