I'm writing a script and I want to require a --host
switch with value, but if the --host
switch isn't specified, I want the option parsing to fail.
I can't seem to figure out how to do that. The docs seem to only specify how to make the argument value mandatory, not the switch itself.
If you do something like this:
Then the
someoptions[:host]
will either be the value from the commandline ornil
(if you don't supply --host and/or no value after --host) and you can test for it easily (and conditionally fail) after the parse:I am assuming you are using optparse here, although the same technique will work for other option parsing libraries.
The simplest method is probably to parse the parameters using your chosen option parsing library and then raise an OptionParser::MissingArgument Exception if the value of host is nil.
The following code illustrates
Running this example with a command line of
simple displays "Host = somehost"
Whilst running with a missing -h and no file name produces the following output
And running with a command line of ./program -h produces