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.

2 Answers2

0

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

neuron
  • 1,976
  • 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 for reference. Also check here 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,816