在 Ruby 中正确转义 shell 参数

Properly escaping shell arguments in Ruby

代码如下:

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}" 与任意 command 一起使用的格式?

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

%Q|these don't need to be escaped /\"'"'{}[]-_+=()!@#$%^&*`~;:<>.,|

使用require 'shellwords'Shellwords.escape 您可以在“shellescape" and "Shellwords

中找到有关这些的更多信息