1

So, I can open files from the shell using ruby with system("start filename"). However, when the file has a space on it, it doesn't work, even though I add the escape \, or if I use shellescape.

Apparently one method would be to first obtain the 8.3 short name of the file, but tried this and didn't succeed. Does anybody knows how can I simply escape a space in this situation? My current code looks like this:

    require 'shellwords'
    filename = "#{$filenamewithspaces}.docx".shellescape
    system("start #{filename}")

Thanks a lot!

Casper
  • 33,403
  • 4
  • 84
  • 79

3 Answers3

1

shellescape is not valid on Windows. On Windows you can use quotes to enclose complex filenames instead. Also note that if you use quotes, you need to provide two arguments to start, as the first parameter is interpreted as a command window title:

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/AFFINITY ] [/WAIT] [/B] [command/program] [parameters]

The easiest way to get around these problems is to use the multi-parameter version of system:

system('start', '', $filenamewithspaces)

If you must use the single-parameter version, then:

system("start \"\" \"#{$filenamewithspaces}\"")

...which is much uglier and less readable, as you can see.

Casper
  • 33,403
  • 4
  • 84
  • 79
  • 2
    I know I should avoid thanks in the comments but until they implement another way to express gratitude here, damn man, thank you!! – Andres Pérez May 20 '18 at 16:33
0

Drop the dollar sign in the variable substitution:

filename = "#{$filenamewithspaces}.docx".shellescape

A tip is to always start irb in your command line and test each command:

2.4.1 :001 > filenamewithspaces = "string with spaces"
 => "string with spaces"
2.4.1 :002 > "#{$filenamewithspaces}"
 => ""
2.4.1 :003 > "#{filenamewithspaces}"
 => "string with spaces"
Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
  • 1
    That is not quite the issue, the dollar sign is to indicate the global variable where I have stored the file name. It doesn't work with or without it, or even if provide the very file name to the start method i.e. system("start my file.txt"), Windows just tells me "Can't find file "my". Same happens even if I try to escape the espace i.e. system("start my\ file.txt") – Andres Pérez May 20 '18 at 13:48
0
filename="my filename should not have spaces but it does.exe"
system("cmd","/c","start",filename)

I'm explicitly writing "cmd", so that it works with both Ruby, native for Windows and Ruby for Cygwin.

If there are no compelling reasons for passing the whole command as a single string, I would always pass the arguments individually as array.

user1934428
  • 19,864
  • 7
  • 42
  • 87