Ruby 1.8的Shellwords.shellescape实现

虽然1.8.7的构建我似乎有一个backported版本的Shellwords::shellescape ,但我知道这个方法是一个1.9function,并且在早期版本的1.8中肯定不支持。 有没有人知道我能找到哪里,无论是Gemforms还是仅作为一个片段,一个强大的独立实现Bourne-shell命令逃避Ruby?

你也可以在Ruby的subversion存储库(这是GPLv2 )的主干中从shellwords.rb复制你想要的东西 :

  def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end 

我最后使用了Escape gem,它具有默认使用引号的附加function,并且只在必要时才进行反斜杠转义。