Skip to content

Repository files navigation

Getoptlong

The GetoptLong class allows you to parse command line options similarly to the GNU getopt_long() C library call. Note, however, that GetoptLong is a pure Ruby implementation.

GetoptLong allows for POSIX-style options like --file as well as single letter options like -f

The empty option -- (two minus symbols) is used to end option processing. This can be particularly important if options have optional arguments.

Installation

Add this line to your application's Gemfile:

gem'getoptlong'

And then execute:

$ bundle

Or install it yourself as:

$ gem install getoptlong

Usage

require'getoptlong'opts=GetoptLong.new(['--help','-h',GetoptLong::NO_ARGUMENT],['--repeat','-n',GetoptLong::REQUIRED_ARGUMENT],['--name',GetoptLong::OPTIONAL_ARGUMENT])dir=nilname=nilrepetitions=1opts.eachdo |opt,arg|
caseoptwhen'--help'puts<<-EOFhello [OPTION] ... DIR-h, --help: show help--repeat x, -n x: repeat x times--name [name]: greet user by name, if name not supplied default is JohnDIR: The directory in which to issue the greeting. EOFwhen'--repeat'repetitions=arg.to_iwhen'--name'ifarg == ''name='John'elsename=argendendendifARGV.length != 1puts"Missing dir argument (try --help)"exit0enddir=ARGV.shiftDir.chdir(dir)foriin(1..repetitions)print"Hello"ifnameprint", #{name}"endputsend

Example command line:

hello -n 6 --name -- /tmp

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/getoptlong.

About

The GetoptLong class allows you to parse command line options similarly to the GNU getopt_long() C library call.

Topics

Resources

Security policy

Stars

7 stars

Watchers

33 watching

Forks

Releases

Packages

Used by

Contributors

Languages