Ruby 1.8的Shellwords.shellescape实现

Avd*_*vdi 5 ruby bash shell escaping sh

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

Bkk*_*rad 9

你也可以在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
Run Code Online (Sandbox Code Playgroud)


Avd*_*vdi 5

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