虽然我拥有的 1.8.7 版本似乎有一个向后移植的版本Shellwords::shellescape
,但我知道该方法是 1.9 的功能,并且在 1.8 的早期版本中绝对不支持。有谁知道我在哪里可以找到以 Gem 形式或仅作为片段的 Bourne-shell 命令转义用于 Ruby 的强大独立实现?
问问题
4582 次
2 回答
9
您不妨从Ruby 的 subversion 存储库(即GPLv2 'd )的主干中的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
于 2009-08-24T00:47:53.113 回答
5
我最终选择了Escape gem,它具有默认使用引号的附加功能,并且仅在必要时使用反斜杠转义。
于 2009-08-24T14:02:51.510 回答