1

How can I properly escape arbitrary commands?


For example:

sudo -u chris sh -c 'echo "\"leftright\""'

The above echos:

"leftright"

How would I echo out:

"left'right"

I've tried the following which I would expect to work but does not:

sudo -u chris sh -c 'echo "\"left\'right\""'

I can't quite get my head round how it is parsed.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Chris Stryczynski
  • 5,178
  • 5
  • 40
  • 80

2 Answers2

0

sudo -u chris sh -c 'echo "\"left'\''right\""'

neuron
  • 1,941
  • 11
  • 20
  • Can you explain this? What other characters do I need to potentially escape to allow any arbitrary commands? – Chris Stryczynski Jul 19 '15 at 19:34
  • It's basically how you handle the opening & the closing quote. For your above example you could also write it as : `sh -c 'echo \"left"'\''"right\"'`. Check [this](http://wiki.bash-hackers.org/syntax/quoting#ansi_c_like_strings) for reference. Also check [here](http://stackoverflow.com/questions/1250079/how-to-escape-single-quotes-within-single-quoted-strings) for a good explanation by liori – neuron Jul 19 '15 at 19:47
0
 sh -c 'echo "\"left'"'"'right\""'

OR

 sh -c 'echo "\"left'\''right\""'

will work.

Either of the above will pass

 echo "\"left'right\""

after -c.

When you're inside a single quoted string there is no escaping other than closing that string.

To pass a single quote, you can either use

 "'"

or

 \'

.

The shell will concatenate adjacent arguments that don't have an input field separator (usually space) in between.

Petr Skocik
  • 28,176
  • 14
  • 81
  • 141