2

I'm using Ruby (2.0) %x{dir} under Windows 7 to run a DOS dir command. The dir being executed is different depending on whether or not dir is quoted.

When the command is bare I get the full output of a DOS dir command:

# sends output of cmd back to program
puts 'run %x{dir}'
puts "dir= " + %x{dir}

What I see on the command line:

run %x{dir}
dir=  Volume in drive C is System
 Volume Serial Number is FFFF-FFFF

 Directory of C:\Users\ ...etc...

08/26/2013  09:16 AM    <DIR>          .
08/26/2013  09:16 AM    <DIR>          ..
01/28/2013  02:28 AM            10,958 AJAX RUG Test.tsc
 ...etc...

When I quote the dir command with either single or double quotes, I get back the output of GnuWin32 dir.exe command which is in the PATH. It took me a while to figure out that the GNU dir was being run. What is causing Ruby to use the dir built into CMD.EXE vs. c:\PROGRA~2\GnuWin32\bin\dir.EXE ???

Also, I've just noticed that my "Pickaxe" and "Ruby Cookbook" use the "%x{}" syntax (BRACES), where the online docs use "%x()" (PARENS) ... is this just a case of general delimiter matching by Ruby?

4

1 回答 1

2

这是 Windows 的特性,而不是 Ruby。这是怎么回事:

Dir 不是可执行文件,而是 Windows/cmd.exe 的本机函数。(它是 cmd.exe 的一部分 - 所以当您键入 dir 并运行内部函数而不是在文件路径中查找“dir.exe”或其他内容时,cmd.exe “陷阱”)。

当您在 cmd 中将某些内容放在引号中时,它会强制 cmd.exe 在路径上查找该命令,而不是通过其内部函数。

您可以通过在 Windows 中打开命令提示符并键入内置命令(在 gnuwin32 中不存在)来测试这一点,例如复制:

>copy
The syntax of the command is incorrect.

>"copy"
'"copy"' is not recognized as an internal or external command,
operable program or batch file.

如果您随后创建包含内容的“copy.cmd”文件:

echo copy.cmd 执行

当你运行时,你会看到:

>"copy"
copy.cmd executed

说得通?基本上引用您从 Ruby 发送到 shell (cmd.exe) 的命令将导致 cmd.exe 的不同解释 - 它会阻止内部/内置 cmd.exe 命令(例如 dir 和 copy)工作,而外部xcopy 等实用程序可以正常工作。

于 2013-09-26T20:28:21.800 回答