代码之家  ›  专栏  ›  技术社区  ›  barlop Sandeep

在windows的ruby中,执行cmd prompt命令move会出现错误“命令语法不正确”

  •  0
  • barlop Sandeep  · 技术社区  · 7 年前

    C:\rubytest>echo asdf>c:\techprogs\azzz.azz
    
    C:\rubytest>del c:\techprogs\azzz.azz
    
    C:\rubytest>echo asdf>c:\techprogs\azzz.azz
    
    C:\rubytest>move /y c:\techprogs\azzz.azz c:\techprogs\autorun.bat
            1 file(s) moved.
    
    C:\rubytest>move /y c:\techprogs\azzz.azz c:\techprogs\autorun.bat
    The system cannot find the file specified.
    
    C:\rubytest>
    

    以上这些都是可以预料的。

    注意,我从来没有得到一个错误,说“命令的语法是不正确的。”

    那就试试红宝石吧

    我有一个简单的文件,只有一行

    C:\rubytest>type syntaxcommandincorrect.rb
    `move /y c:\techprogs\azzz.azz c:\techprogs\autorun.bat`
    
    C:\rubytest>
    

    但它给出了语法上的错误

    C:\rubytest>del c:\techprogs\azzz.azz
    
    C:\rubytest>ruby syntaxcommandincorrect.rb
    The syntax of the command is incorrect.
    
    C:\rubytest>echo asdf>c:\techprogs\azzz.azz
    
    C:\rubytest>ruby syntaxcommandincorrect.rb
    The syntax of the command is incorrect.
    
    C:\rubytest>
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   barlop Sandeep    7 年前

    这里的问题可能是在插入的Ruby字符串中有重要意义的反斜杠,双引号,但也有反斜杠样式的shell命令。

    因此,您的命令被解释为:

    move /y c:^Iechprogs^Gzzz.azz c:^Iechprogs^Gutorun.bat
    

    在哪里? ^I "\t" 是制表符,和 ^G "\a" bell character

    取而代之的是:

    `move /y c:\\techprogs\\azzz.azz c:\\techprogs\\autorun.bat`
    

    require 'fileutils'
    
    FileUtils.mv('c:\techprogs\azzz.azz', 'c:\techprogs\autorun.bat', force: true)
    

    这里我用单引号来避免双反斜杠和 force: true /y FileUtils.mv ,是一整套有用的文件和目录操作实用程序的一部分。

    巴洛普添加

    确认上述情况。双反斜杠修复了它,我看到通过执行puts`echo copy/y c:\techprogs…`单反斜杠会发生什么,我看到techprogs的t被删除,如下所示 c:\techprogs 成为 c:<ascii-9>echprogs. \autorun 成为 <ascii-7>utorun

    C:\rubytest>cmdoutoutwithoutinitbat.rb | xxd
    0000000: 6162 6364 6566 670d 0a63 6f70 7920 2f79  abcdefg..copy /y
    0000010: 2063 3a09 6563 6870 726f 6773 0775 746f   c:.echprogs.uto
    0000020: 7275 6e2e 6261 7420 633a 0965 6368 7072  run.bat c:.echpr
    0000030: 6f67 7307 7a7a 7a2e 617a 7a0d 0a61 6263  ogs.zzz.azz..abc
    0000040: 6465 6667 0d0a 6d6f 7665 202f 7920 633a  defg..move /y c:
    0000050: 0965 6368 7072 6f67 7307 7a7a 7a2e 617a  .echprogs.zzz.az
    0000060: 7a20 633a 0965 6368 7072 6f67 7307 7574  z c:.echprogs.ut
    0000070: 6f72 756e 2e62 6174 0d0a                 orun.bat..
    
    C:\rubytest>