Objective-C shell 转义
如何在 ObjectivesC 中转义 shell 命令的参数?
ruby 库有 Shellwords
(shellescape
用于 NSString,shelljoin
用于 NSArray,我不需要 shellsplit
)。我确实需要一个转义字符串,我知道 NSTask,我不需要执行该命令。
How do you escape arguments for shell commands in ObjectivesC?
The ruby library has Shellwords
(shellescape
for NSString, shelljoin
for NSArray, I don't need shellsplit
). And I really need an escaped string, I know about NSTask, I don't need to execute that command.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果使用单引号,则转义 shell 的内容非常容易。了解 shell 引用的重要一点是,您可以在同一参数中连接具有不同引用样式的字符串,甚至是不带引号的字符串。例如,
'one one'two'third"four"
混合了所有 3 种引用样式,并最终将字符串“onetwothirdfour”作为单个参数传递。另一件需要理解的事情是,除了引用之外,您还可以反斜杠转义特殊字符。最终结果是像'one 二'\''三四'
这样的字符串,其计算结果为带有单引号的字符串“一二'三四”。通过使用此技巧,您可以轻松地引用任何字符串,方法是将所有单引号替换为序列'\''
,然后将整个字符串括在一对单引号中。如果您有以下字符串:
并且应用了这个简单的转换,您最终会得到结果
,并且 shell 会将其计算回原始字符串并作为单个参数进行处理。
NSString 上的以下类别应该可以轻松完成此转换:
Escaping content for the shell is pretty easy if you use single quotes. The important thing to understand about shell quoting is that you can concatenate strings with different quoting styles, and even unquoted strings, in the same argument. For example,
'one two'three" four"
mixes all 3 quoting styles, and ends up passing the string "one twothree four" as a single argument. The other thing to understand is that outside of quoting, you can backslash-escape special characters. The end result of this is a string like'one two'\''three four'
evaluates to the string "one two'three four", with the single quote. By using this trick, you can easily quote any string by replacing all single-quotes with the sequence'\''
and then wrapping the entire string in a single pair of single quotes.If you have the following string:
and you apply this simple transformation you end up with
and this gets evaluated back to the original string by the shell and handled as a single argument.
The following category on NSString should accomplish this transformation easily:
请参阅
NSString
此处。有很多晦涩难懂的,但我认为没有一个适合你的工作。你需要自己写一个。如果该方法调用相对较少,我只需从 Objective-C 内部调用 ruby 二进制文件并使用 shellescape,然后检索结果;重新发明轮子是愚蠢的。
See the list of methods of
NSString
here. There are many obscure ones, but I don't think there's any that fits your job. You need to write one yourself.If that method is called relatively infrequently, I would just call
ruby
binary from inside Objective-C and useshellescape
, and then retrieve the result; it's stupid to re-invent the wheel.