代码之家  ›  专栏  ›  技术社区  ›  recursive

在windows中编写rakefile运行命令的最佳方法是什么?

  •  3
  • recursive  · 技术社区  · 16 年前

    作为一个例子,我想在rake下运行以下命令。

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

    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"
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   Jeff Dallien    16 年前

    双反斜杠解释为转义的单反斜杠。你应该转义字符串中的每个反斜杠。

    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
    
    推荐文章