title: how to escape quotes in command argument to sh -c?
body: <p>The shell command cmd may have whitespace and single and double quotes.</p>
  
  <p>How to escape these quotes to correctly pass the command to a POSIX shell:</p>
  
  <p><code>&gt;dash -c '</code>cmd<code>'</code></p>
  
  <p>The other question pointed as a dup, asks about double quotes.  One of the answers there is probably going to work - to split the command and use concatenated quotes.  For example, if cmd were</p>
  
  <pre><code>cd "dir"; ls 'foobar'
  </code></pre>
  
  <p>then we would transform that into</p>
  
  <pre><code>&gt;dash -c 'cd "dir"; ls '"'foobar'"
  </code></pre>
  
  <p>This is messy...  is there no easier way?</p>
  
  <p>Added: it seems like nobody understands me...  I just want a general procedure, an algorithm, that takes on input, a string (to be completely precise, made out of printable ASCII characters from 0 to 127 in the ASCII table), and outputs, the second string.  The requirement is that if the first string is executed like this</p>
  
  <pre><code>POSIX_shell&gt;string1
  </code></pre>
  
  <p>the result is the same as</p>
  
  <pre><code>&gt;POSIX_shell -c string2
  </code></pre>
  
  <p>Am I more clear now, please let me know.</p>