例如,我想在 rake 下运行以下命令。
robocopy C:\Media \\other\Media /mir
我能够开始工作的 rakefile 是
def sh(str)
str.tr!('|', '\\')
IO.popen(str) do |pipe|
pipe.each do |line|
puts line
end
end
end
task :default do
sh 'robocopy C:|Media ||other|Media /mir'
end
然而,字符串文字的处理很尴尬。
如果我使用 heredoc 输入字符串文字
<<HEREDOC
copy C:\Media \\other\Media /mir
HEREDOC
我得到了错误
rakefile.rb:15: Invalid escape character syntax
copy C:\Media \\other\Media /mir
^
rakefile.rb:15: Invalid escape character syntax
copy C:\Media \\other\Media /mir
^
如果我使用单引号,其中一个反斜杠会丢失。
irb(main):001:0> 'copy C:\Media \\other\Media /mir'
=> "copy C:\\Media \\other\\Media /mir"
最佳答案
双反斜杠被解释为转义的单反斜杠。您应该转义字符串中的每个反斜杠。
irb(main):001:0> puts 'robocopy C:\\Media \\\\other\\Media /mir'
robocopy C:\Media \\other\Media /mir
或者,如果您真的不想转义反斜杠,您可以使用带有单引号标识符的此处文档。
irb(main):001:0> <<'HEREDOC'
irb(main):002:0' copy C:\Media \\other\Media /mir
irb(main):003:0' HEREDOC
=> "copy C:\\Media \\\\other\\Media /mir\n"
irb(main):004:0> puts _
copy C:\Media \\other\Media /mir
关于windows - 编写 rakefile 以在 Windows 中运行命令的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/526386/