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

标签 windows ruby command-line command rake

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

相关文章:

batch-file - 到 "Call"或 "Not to Call"一个批处理文件?

windows - Vim 在每次保存后插入 _viminfo 文件

ruby-on-rails - 我如何才能在 Windows 上安装 curb?

ruby - 如何通过 Net::HTTP::Get 下载二进制文件?

linux - 找不到 debian linux gvfs-copy 命令

Linux 'find' 仅针对当前文件夹和指定文件夹

c - 为什么我必须手动将 OpenGL 库与 MinGW 链接起来?

windows - 从卷影副本备份

c# - C# 中 ionic zip 的替代品是什么?

ios - 安装 Cocoapods 0.35.0 时出错