Skip to content

Instantly share code, notes, and snippets.

@adam12
Forked from rkumar/gist:445735
Created November 30, 2023 15:31
Show Gist options
  • Save adam12/acb2b08b7bc1a711fdf0afe503667c2e to your computer and use it in GitHub Desktop.
Save adam12/acb2b08b7bc1a711fdf0afe503667c2e 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment