2009-02-08 93 views
3

举个例子,我想在rake下运行下面的命令。编写rakefile在Windows中运行命令的最佳方法是什么?

robocopy C:\Media \\other\Media /mir 

的Rake文件我能得到的工作是

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 
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" 

回答

3

双反斜杠被解释为转义的单个反斜杠。您应该转义字符串中的每个反斜杠。或者,如果你真的不想逃避反斜杠,你可以使用带有单引号标识符的here doc。

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 
+0

是的,但像我列在问题中的代码,它是尴尬逃脱所有反斜杠字符。 – Frank 2009-02-09 20:54:18

相关问题