Ruby escape ARGV argument or string as argument to shell command

你。 提交于 2019-12-20 11:11:02

问题


Ok this is driving me crazy:

`ls #{"/media/music/Miles Davis"}`

fails because of the space between "Miles" and "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.

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.

How do escape whatever you insert in a shellout?


回答1:


Use require 'shellwords' and Shellwords.escape, which will fix this sort of stuff for you:

http://apidock.com/ruby/Shellwords/shellescape




回答2:


Stay away from building shell strings whenever possible, it is a fine vector for arbitrary code execution.

In this case, you could use popen, which does the escaping for you:

IO.popen(['printf', 'a b']) do |f|
  var = f.read
end



回答3:


Double quotes also works:

`ls "#{'/media/music/Miles Davis'}"`

or

`ls "#{ARGV[0]}"`


来源:https://stackoverflow.com/questions/6921599/ruby-escape-argv-argument-or-string-as-argument-to-shell-command

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