Fork me on GitHub

Project Notes

#252

Using the getopts utility for parsing options in shell scripts.

Notes

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.

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

Parsing Options

while getopts "p:v" opt
do
  case $opt in
  p)
    # handling option with parameter -p XX
    p=$OPTARG
    ;;
  v)
    # handling option flag -v
    v=true
    ;;
  \?)
    # handling invalid options
    ;;
  esac
done

Handling Boolean Option Flags

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

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

Handling Options With Parameters

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

$ ./example.sh
got p:
got v:
$ ./example.sh -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.

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

Usage

  ./example.sh -p value # set "p" to value
  ./example.sh -v       # set "v" true
  ./example.sh -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):

$ ./example.sh 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.

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

Credits and References

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

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.

LittleArduinoProjects LittleModelArt More on my blog