Warning: for aksakals article is unlikely to be useful. And even it will be harmful. System administrators who use ruby to write scripts are strongly recommended.
For parsing command line arguments, I usually used the GetOpt library. This is a rather inconvenient library and I was happy stumbled upon
Docopt.Start.
Starting to use it is quite simple: to teach your script to parse the output string, you first need to connect the library:
')
require 'docopt'
And after that you can try to initialize the variable and assign it the appropriate value.
doc =<<EOF Usage:
Now it is enough to pass the variable as a parameter:
begin arguments = Docopt::docopt(doc) rescue Docopt::Exit => e puts e.message exit end
If the arguments are not specified or your script is called with the
-h or
–help key, the message that you entered is displayed.
In other cases, the library itself will parse the string from the
doc variable and add everything to the hash, which we have already assigned to the
arguments variable.
~/myscript add test argument2 --input=local.txt {"add"=>true, "<opt1>"=>"test", "<opt2>"=>"argument2", "--input"=>"local.txt", "--verbose"=>false, "--help"=>false}
As we can see, the data is conveniently located in the hash, and we can take them from there using standard mechanisms.
puts arguments["<opt1>"] puts arguments["--input"]
The library allows you to use optional and strictly required parameters. Mandatory are indicated with parentheses
() , and optional square brackets
[]Among other things, we can introduce several standards for using them under the
Usage line
: Usage:
You can also set default values for variables under the
Options line::
--input=<something> [default: my.txt]
Now the value in the hash of
arguments [- input] will be my.txt, unless otherwise specified.
Out of trouble, the $ stdin channel will have to be used to read input.
$stdin.gets.chomp
the end
Actually this is all that you should know about this library.