-1

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 \ .

2 Answers2

2

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/echos, 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.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
0

use 4 backslashes instead of 2

Dr.venom
  • 39
  • 3
  • Could you explain why the user is getting only a single backslash, and why your suggestion fixes that? Take into account that a `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
  • The OP says that he has a very long string with many occurencies of \\ and when it is printed the first backslash is removed from each occurence, and that is the problem that he wants a solution to. so from the behavior of his bash, i can say my bash does the same and suggested that he use 4 backslashes because one backslash escapses the following one, with 2 escapes he gets 2 backslashes printed as he wants... – Dr.venom Jan 22 '21 at 19:10