Let’s say I have shell programs a,b,c, each one executing a command from the other one. For some reasons, I need quotes. Example:
a 'b 'c 'echo test'''
So a shall call b, which shall call c, which will call ‘echo test’. You already see that my quotes will be wrong interpreted. Also, note that a, b, and c are C-programs calling system().
Is there any solution to do that, preserving the quotes?
I have no ready solution for C, but in this case, it is advisable to take your string-to-be-quoted, replace every
'with'\''and enclose the whole stuff in'.echo testThat can happily be put in''and given toc:c 'echo test'.Then you want to give that string to
b. Here it starts, because the said string contains's, so you do'+c '\''echo test'\''+'which you give to b:b 'c '\''echo test'\'''.What happens here? You have concatenated several concatenated parts for
b‘s argument:'c ', which becomes justc `,\', which becomes''echo test', which isecho testafter stripping the quotes,\'again ->', and''which is nothing and only exists because there is a'at the end of the original string. It can be omitted if processed manually, but isn’t worth the effort in an algorithm.So you get
c 'echo test'after dequoting that, which shows that the said algorithm should work.Now you do this process to
b 'c '\''echo test'\'''again in order to have an argument fora: so you’ll geta 'b '\''c '\''\'\'''\''echo test'\''\'\'''\'''\'''.\s:system("a 'b '\\''c '\\''\\'\\'''\\''echo test'\\''\\'\\'''\\'''\\'''");.If you do the said optimization on starting, ending and successive
's, you getand
resp.
.
Alternatively, you could work without the
'and just quote the spaces and the ‘\’s, but that would probably even trickier…Let me try:
echo test->echo\ test->c echo\ test.b c\ echo\\\ test.a b\ c\\\ echo\\\\\\\ test.system("a b\\ c\\\\\\ echo\\\\\\\\\\\\\\ test").Quote ugly, but it works.
Tested with
as
a,bandcandas
test.pyand called withAs python has in this case the same quoting rules as C, it is a sufficient test.