2010-08-17

[Tip]escape shell metacharacters

There is an efficient method to make arbitrary string to escape shell metacharacters while using single-quote('). That is, just suspend a string by ('), add(\'), then continue the string by (').

For example, in Python:
def escapeShellArg(string):
    return u"'"+string.replace(u"'",u"'\\''")+u"'"
This is because UNIX shell explain
testcmd 'test'\''string'
as
testcmd "test'string"
Besides, program testcmd will receive argv=["testcmd","test'string"]. Thus, we could efficiently escape shell metacharacters without regular expression library or other complex string processing library.

沒有留言:

張貼留言