Skip to content

Instantly share code, notes, and snippets.

@rkumar
Created June 20, 2010 10:47
Show Gist options
  • Save rkumar/445735 to your computer and use it in GitHub Desktop.
Save rkumar/445735 to your computer and use it in GitHub Desktop.
ruby's OptionParser to get subcommands
#!/usr/bin/env ruby -w
## Using ruby's standard OptionParser to get subcommand's in command line arguments
## Note you cannot do: opt.rb help command
## other options are commander, main, GLI, trollop...
# run it as
# ruby opt.rb --help
# ruby opt.rb foo --help
# ruby opt.rb foo -q
# etc
require 'optparse'
options = {}
subtext = <<HELP
Commonly used command are:
foo : does something awesome
baz : does something fantastic
See 'opt.rb COMMAND --help' for more information on a specific command.
HELP
global = OptionParser.new do |opts|
opts.banner = "Usage: opt.rb [options] [subcommand [options]]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
opts.separator ""
opts.separator subtext
end
#end.parse!
subcommands = {
'foo' => OptionParser.new do |opts|
opts.banner = "Usage: foo [options]"
opts.on("-f", "--[no-]force", "force verbosely") do |v|
options[:force] = v
end
end,
'baz' => OptionParser.new do |opts|
opts.banner = "Usage: baz [options]"
opts.on("-q", "--[no-]quiet", "quietly run ") do |v|
options[:quiet] = v
end
end
}
global.order!
command = ARGV.shift
subcommands[command].order!
puts "Command: #{command} "
p options
puts "ARGV:"
p ARGV
@tciuro
Copy link

tciuro commented Nov 10, 2015

I only see the following when I invoke with tool with -h:

Usage: opt.rb [options] [subcommand [options]]
    -v, --[no-]verbose               Run verbosely

Commonly used command are:
   foo :     does something awesome
   baz :     does something fantastic
See 'opt.rb COMMAND --help' for more information on a specific command.

Any idea why the subcommands help is not being printed? I was expecting the help text for -f and -q to be included in the output.

@alkiskal
Copy link

alkiskal commented Jan 9, 2016

The first level of help is just the subtext. As specified by "See 'opt.rb COMMAND --help' for more information on a specific command." you have to include the command and then --help, so it acts as an argument for the command. Then the help for that particular command will be printed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment