Reputation: 1026
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?
Upvotes: 2
Views: 245
Reputation: 2344
This is a peculiarity of Windows, not Ruby. What's going on is this:
Dir is not an executable but a native function of Windows/cmd.exe. (It's part of cmd.exe - so cmd.exe "traps" when you type dir and runs an internal function rather than looking for "dir.exe" or something out on your file path).
When you put something in quotes in cmd, it forces cmd.exe to look for that command on the path, not via it's internal functions.
You can test this by opening a command prompt in Windows and typing a built-in command (that doesn't exist in gnuwin32) such as copy:
>copy
The syntax of the command is incorrect.
>"copy"
'"copy"' is not recognized as an internal or external command,
operable program or batch file.
If you then create "copy.cmd" file with contents:
echo copy.cmd executed
when you run, you'll see:
>"copy"
copy.cmd executed
Make sense? Basically quoting the command you send to the shell (cmd.exe) from Ruby will cause a different interpretation by cmd.exe - it will prevent internal/built-in cmd.exe commands (such as dir and copy) from working, whereas external utils such as xcopy will work fine.
Upvotes: 2