From: Mark Volkmann Date: 2006-02-18T04:38:09+09:00 Subject: Re: getoptlong, getopt, parseopt, which one to use for command line tool? On 2/17/06, Charlie Bowman wrote: > There seems to be several options out there. Which one should be used > when creating command line tools? I was just looking into that last night, but in my case I wanted to stick with a standard library so the choices were GetoptLong and OptionParser. Of those it seems to me that OptionParser is a little better. Here's some example code that demonstrates using it. If I'm not using it in the best way, I'm definitely open to feedback. I'm also interested in hearing whether there is a better alternative. # To get usage info.: ruby optionparserdemo.rb -h # To take defaults: ruby optionparserdemo.rb # To specify all options: ruby optionparserdemo.rb -n Mark -d 19 -c blue -f # Example of an invalid option: ruby optionparserdemo.rb -z 42 # Example of an invalid value: ruby optionparserdemo.rb -c yellow # Example of another invalid value: ruby optionparserdemo.rb -d foo require 'optparse' # Create a Hash containing option default values. # Specified options will replace these. options = {:name=>'unknown', :duration=>5, :color=>'red', :final=>false} # Configure an OptionParser. parser = OptionParser.new parser.on('-h', '--help', 'displays usage information') do puts parser exit end parser.on('-n=NAME', '--name=NAME', 'name of person running experiment') do |v| options[:name] = v end parser.on('-d=DURATION', '--duration=DURATION', Integer, 'duration in seconds') do |v| options[:duration] = v end parser.on('-c=COLOR', '--color=COLOR', %w(red green blue), 'color of light') do |v| options[:color] = v end parser.on('-f', '--final', TrueClass, 'true if final run; false otherwise') do |v| options[:final] = true end # Parse command-line options. begin parser.parse($*) rescue OptionParser::ParseError puts $! exit end # Output the options that will be used. puts "Options are #{options.inspect}" -- R. Mark Volkmann Partner, Object Computing, Inc.