【问题标题】:What is the best way to write a rakefile to run commands in windows?编写 rakefile 以在 Windows 中运行命令的最佳方法是什么?
【发布时间】:2010-10-06 07:09:36
【问题描述】:

例如,我想在 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"

【问题讨论】:

    标签: windows ruby command-line command rake


    【解决方案1】:

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

    irb(main):001:0> puts 'robocopy C:\\Media \\\\other\\Media /mir'
    robocopy C:\Media \\other\Media /mir
    

    或者,如果您真的不想转义反斜杠,您可以使用带有单引号标识符的 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
    

    【讨论】:

    • 是的,但就像我在问题中列出的代码一样,转义所有反斜杠字符很尴尬。
    • 我认为简单地转义字符串中的反斜杠是最不尴尬的,但我用一个可行的 here doc 语法更新了答案。
    • 好的,太好了! HEREDOC 是要走的路……这是我第一次看到
    • 引号的类型表示如何处理字符串。用于执行 shell 命令的反引号 (`) 也是有效的。见ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/…
    猜你喜欢
    • 2011-06-13
    • 2019-11-15
    • 1970-01-01
    • 2010-09-15
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多