bash Ruby 将 ARGV 参数或字符串转义为 shell 命令的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6921599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby escape ARGV argument or string as argument to shell command
提问by ulver
Ok this is driving me crazy:
好吧,这让我发疯:
`ls #{"/media/music/Miles Davis"}`
fails because of the space between "Miles" and "Davis"
由于“Miles”和“Davis”之间的空格而失败
Say I write a ruby script and a user passes file path as an argument. How do I escape it and feed to a shell-out command. Yes, yes, I know, shelling out should be avoided. But this is a contrived example, I still need this.
假设我编写了一个 ruby 脚本,并且用户将文件路径作为参数传递。我如何转义它并提供给 shell-out 命令。是的,是的,我知道,应该避免炮轰。但这是一个人为的例子,我仍然需要这个。
I would do system("ls", ARGV[0]), but it doesn't return the stdout output of ls as a string, which is what backticks do well.
我会这样做system("ls", ARGV[0]),但它不会将 ls 的 stdout 输出作为字符串返回,这正是反引号做得好的地方。
How do escape whatever you insert in a shellout?
如何逃避您在 shellout 中插入的任何内容?
回答by Casper
Use require 'shellwords'and Shellwords.escape, which will fix this sort of stuff for you:
使用require 'shellwords'and Shellwords.escape,它将为您解决此类问题:
回答by fetsh
Double quotes also works:
双引号也有效:
`ls "#{'/media/music/Miles Davis'}"`
or
或者
`ls "#{ARGV[0]}"`

