how to escape quotes in command argument to sh -c? [duplicate]

老子叫甜甜 提交于 2019-12-24 06:13:05

问题


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

How to escape these quotes to correctly pass the command to a POSIX shell:

>dash -c 'cmd'

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

cd "dir"; ls 'foobar'

then we would transform that into

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

This is messy... is there no easier way?

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

POSIX_shell>string1

the result is the same as

>POSIX_shell -c string2

Am I more clear now, please let me know.


回答1:


First of all, try to avoid messy things as you mentioned. If you have to, keep it simple, all double quotes inside single quote will have no problem. All single quote inside a 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\""


来源:https://stackoverflow.com/questions/37758773/how-to-escape-quotes-in-command-argument-to-sh-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!