Search code examples
rubybashcommand-line-argumentsoptionparser

Why does this command fail when I use a # in command line args?


I have the following command:

ruby SaveAllDatabases.rb 192.168.0.15 1024 -r #0-D --non-interactive

It's a fairly basic command in which I run a ruby script with some command line arguments. The -r argument is a regular expression (#0-D).

If I run this command on Windows (using the standard Windows command prompt), everything runs as expected, but if I try and run the same command on Linux (with the same version of ruby installed). I get the following error:

/usr/lib/ruby/1.8/optparse.rb:451:in `parse': missing argument: -r (OptionParser::MissingArgument)
  from /usr/lib/ruby/1.8/optparse.rb:1295:in `parse_in_order'
  from /usr/lib/ruby/1.8/optparse.rb:1254:in `catch'
  from /usr/lib/ruby/1.8/optparse.rb:1254:in `parse_in_order'
  from /usr/lib/ruby/1.8/optparse.rb:1248:in `order!'
  from /usr/lib/ruby/1.8/optparse.rb:1339:in `permute!'
  from /usr/lib/ruby/1.8/optparse.rb:1360:in `parse!'
  from SaveAllDatabases.rb:256

If I take the hash/pound (#) symbol out of the regex, the command runs fine. I've done a test, and the command line doesn't seem pass anything after the # into the argv array.

Why is this, and how can I work round it?


Solution

  • Take a look at the highlighting on your posted code. Notice how the # and everything after it are in gray? This is how you do comments in bash. Everything after the # is considered a comment.

    echo "This will show on the screen" # This is a comment, it's ignored 
    

    The solution is to quote the comment:

    ruby SaveAllDatabases.rb 192.168.0.15 1024 -r '#0-D' --non-interactive
    

    EDIT: Here's a link with more information.