4

Consider this bash example:

TESTA="testing a \\\"string right here\\\""
echo $TESTA
# testing a \"string right here\"

The output is as expected: the first pair of backslashes resolved to a single backslash (\), and the next escaped double quote \" got expanded to a double quote ("), so the final merged result is \".

Now this is the strange part for me:

TESTB=$(echo $TESTA)
echo $TESTB
# testing a \"string right here\"

Here I would have expected the contents of $TESTB to be, indeed, testing a \"string right here\" - but I expected that when that is printed out, the escaped double quote \" would have expanded to just a double quote ", and so I expected the printed result to be with unescaped double quotes, that is testing a "string right here"; but that's not what I get echoed, I get the same escaped doublequotes as the contents...

So, is there a way to "expand" the $TESTA so it ultimately contains unescaped double quotes? (I tried echo -e which should "enable interpretation of backslash escapes", but it doesn't help)...


EDIT: it turns out, for this particular case, TESTB=$(eval echo "$TESTA") ; echo $TESTB will indeed result with testing a "string right here" -- but I don't want to eval: if I'm building a command line string this way, using eval will be trouble. So maybe I should better rephrase: how can I expand escaped double-quotes like this, as a result of a string operation of sorts (calling an extern program is OK, as long as the string itself is not eval'd)

sdaau
  • 36,975
  • 46
  • 198
  • 278
  • No, you are backslash escaping the backslash so it is seen as a normal character, i dont know why you would expect anything else ? –  Jul 21 '14 at 08:10
  • What is it that you really want to accomplish? If you are trying to build up a command line, and you are using bash, ksh or zsh -- that is, a shell with arrays -- then you would be far better off using an array than trying to juggle quotes. See the bash faq: http://mywiki.wooledge.org/BashFAQ/050 ("I'm trying to put a command in a variable, but the complex cases always fail!") – rici Jul 21 '14 at 16:06
  • What would you think if you used `\x22` instead of `\"` in the string. e.g.: `TESTA="testing a \x22string right here\x22"; echo -e $TESTA` – László Szilágyi May 23 '21 at 20:02

1 Answers1

2

How about this:

TESTA="testing a \"string right here\""
echo $TESTA

is this what you were looking for?

by the way you said

TESTB=$(eval echo "$TESTA") ; echo $TESTB will indeed result with testing a "string right here"

but it actually prints

 testing a string right here
SamLosAngeles
  • 2,660
  • 2
  • 14
  • 12
  • Thanks @user3600166 - for other reasons, I need to have the original string escaped with three backslashes inside; so no, that is not what I'm looking for. Where did you try that `TESTB=$(eval echo "$TESTA") ; echo $TESTB`? I did all those directly in a shell - if you tried them in a script, the behavior may be different... Cheers! – sdaau Jul 21 '14 at 04:52