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

4
  • 1
    Possible duplicate of Why is printf better than echo? Commented Jan 22, 2021 at 15:11
  • 2
    Is that on Solaris or macOS? It's rare for bash's echo to expand backslash sequences by default. In any case, you don't want to use echo to output arbitrary strings as noted in the Q&A I linked to. Commented Jan 22, 2021 at 15:12
  • Do you have the xpg_echo shell option set in your shell? Or are you actually using -e with echo (but forgot to type that in the question)? Commented Jan 22, 2021 at 15:21
  • shopt tells me xpg_echo is unset Commented Jan 22, 2021 at 15:40

2 Answers 2

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.

0

use 4 backslashes instead of 2

2
  • 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. Commented Jan 22, 2021 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... Commented Jan 22, 2021 at 19:10

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.