Fork me on GitHub

Project Notes


Using the getopts utility for parsing options in shell scripts.


getopts is a POSIX system utility available on most Unix/Linux style distributions.

It helps scripts retrieve options and option-arguments from a list of parameters.

$ ./ -v -p 35
got p: 35
got v: true

Parsing Options

while getopts "p:v" opt
  case $opt in
    # handling option with parameter -p XX
    # handling option flag -v
    # handling invalid options

Handling Boolean Option Flags

Accepting boolean option flags like -v with while getopts "v" ...:

$ ./
got p:
got v:
$ ./ -v
got p:
got v: true

Handling Options With Parameters

Accepting boolean option flags like -p XX with while getopts "p:" ...:

$ ./
got p:
got v:
$ ./ -p 42
got p: 42
got v:

Invalid Parameters

getopts will raise an error if parameters that don’t match the options spec are provided e.g.

$ ./ -x
./ illegal option -- x
(handling an error)


  ./ -p value # set "p" to value
  ./ -v       # set "v" true
  ./ -h       # this message

Accepting additional parameters

Note: getopts does not remove options from the shell arguments

If unknown argments comes before options, the options parsing fails silently (effectively skipped):

$ ./ bogative -v -p 42
got p:
got v:

If arguments other than those parsed by getopts are required, they should come first and be removed from the args (using shift) before getopts parsing.

$ ./ magic -v -p 42
magic: detected special argument
got p: 42
got v: true

Credits and References

About LCK#240 bash
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.