Just thought I'd document this: I'm trying something very simple - set env variable in bash
, and print it out:
$ bash -c "a=1; echo a$a;"
a
$ bash -c "a=1; echo a\$a;"
a1
Now I'd want this same thing, but called as argument of sh
(on my system, ls -la $(which sh)
gives /bin/sh -> dash
):
$ sh -c "bash -c "a=1; echo a\$a;""
a$a
# obviously I have to escape inner quotes:
$ sh -c "bash -c \"a=1; echo a\$a;\""
a
# escape the dollar once more?
$ sh -c "bash -c \"a=1; echo a\\$a\" "
sh: Syntax error: Unterminated quoted string
# nope... inner single quotes, then?
$ sh -c "bash -c 'a=1; echo a$a;'"
a
# nope... escape the single quotes?
$ sh -c "bash -c \'a=1; echo a$a;\'"
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
a
sh: ': not found
# nope... escape the dollar too?
$ sh -c "bash -c \'a=1; echo a\$a;\'"
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
a
sh: ': not found
So, my question would be - what is the proper syntax for escaping, so that sh -c [bash -c ...]
gives the same result as just bash -c ...
?
sh -c "bash -c 'a=1; echo a\$a \'"
works by happenstance, but it's a bit bizarre. The final single quote is not escaped:\'
retains the backslash inside double quotes. The command passed tobash
isa=1; echo a$a \
, and that final backslash happens to have no effect. – Gilles 'SO- stop being evil' Apr 24 '13 at 01:22