Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape quotes in command arguments to sh -c? [duplicate]

The shell command may have whitespace and single and double quotes.

How can I escape these quotes to correctly pass the command to a POSIX shell, as in the following?

>dash -c 'command'

The other question pointed as a duplicate and 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 the command were

cd "dir"; ls 'foobar'

then we would transform that into

>dash -c 'cd "dir"; ls '"'foobar'"

This is messy... Isn't there an easier way?

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

POSIX_shell>string1

The result is the same as

>POSIX_shell -c string2
like image 221
Mark Galeck Avatar asked Sep 03 '25 03:09

Mark Galeck


1 Answers

First of all, try to avoid messy things as you mentioned. If you have to, keep it simple, and keeping all double quotes inside single quote will not have any problem. All single quotes inside double quotes should not be a problem.

#Example:
echo '"These are double quoted"'
echo "'These are single quoted'"

Third (messy and avoid this if possible), any single quote that you want inside a single quote has to be escaped using multiple quotes.

echo ''"'"'These are all single quoted, but messy'"'"''

Fourth, a double quote inside a double quote should be escaped using a backslash \:

echo "\"These are double quoted\""
like image 140
iamauser Avatar answered Sep 05 '25 01:09

iamauser