在Ruby中正确转义shell参数

在Ruby中正确转义shell参数,ruby,rake,rakefile,Ruby,Rake,Rakefile,代码如下: desc "Find 301 errors on production servers" task :find301 do command = "grep 'HTTP/1.1\" 301' /var/log/httpd/*ssl-access.log | grep -v 'gclid' | awk '{print \$7}' | sort | uniq -c | sort -nr" production_servers.each do |server| sh "ss

代码如下:

desc "Find 301 errors on production servers"
task :find301 do
  command = "grep 'HTTP/1.1\" 301' /var/log/httpd/*ssl-access.log | grep -v 'gclid' | awk '{print \$7}' | sort | uniq -c | sort -nr"

  production_servers.each do |server|
    sh "ssh root@#{server} #{command}"
  end
end
是否有更好的方法来转义shell命令,最好采用允许将sh ssh root@{server}{command}用于任意命令的格式?

您可以使用%q和%q版本,但仍需要指定分隔符

%Q|these don't need to be escaped /\"'"'{}[]-_+=()!@#$%^&*`~;:<>.,|
您可以使用%q和%q版本,但仍需要指定分隔符

%Q|these don't need to be escaped /\"'"'{}[]-_+=()!@#$%^&*`~;:<>.,|
使用require'shellwords'和shellwords.escape 您可以在和

使用require'shellwords'和shellwords.escape中找到有关这些的更多信息
您可以在和中找到有关这些的详细信息。不要使用字符串操作生成命令行,使用或的多参数形式并完全绕过shell。不要使用字符串操作生成命令行,使用或的多参数形式并完全绕过shell。shellwords monkey string,我喜欢:foo bar.shellescape==foo\\barshellwords monkey patches String,我喜欢:foo bar.shellescape==foo\\bar