ArticleslgStudy

science

Getopts

Getopts is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Getopts rather than just read about it. In short: getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt.

Key takeaways

  • Getopts belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Getopts to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Getopts from memory before moving on to harder problems.

Reference excerpt

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt. The predecessor to getopts was the external program getopt by Unix System Laboratories.

History The original getopt had several problems: it could not handle whitespace or shell metacharacters in arguments, and there was no ability to disable the output of error messages. getopts was first introduced in 1986 in the Bourne shell shipped with Unix SVR3. It uses the shell's own variables to track the position of current and argument positions, OPTIND and OPTARG, and returns the option name in a shell variable. Earlier versions of the Bourne shell did not have getopts. In 1995, getopts was included in the Single UNIX Specification version 1 / X/Open Portability Guidelines Issue 4. As a result, getopts is now available in shells including the Bourne shell, KornShell, Almquist shell, Bash and Zsh. The getopts command has also been ported to the IBM i operating system. The modern usage of getopt was partially revived mainly due to an enhanced implementation in util-linux. This version, based on the BSD getopt, not only fixed the two complaints around the old getopt, but also introduced the capability for parsing GNU-style long options and optional arguments for options, features that getopts lacks. The various BSD distributions, however, stuck to the old implementation.

Usage The usage synopsis of getopt and getopts is similar to its C sibling:

getopt optstring [parameters] getopts optstring varname [parameters]

The optstring part has the same format as the C sibling. The parameters part simply accepts whatever one wants getopt to parse. A common value is all the parameters, "$@" in POSIX shell. This value exists in getopts but is rarely used, since it can just access the shell's parameters. It is useful with resetting the parser, however. The varname part of getopts names a shell variable to store the option parsed into. The way one uses the commands however varies a lot:

getopt simply returns a flat string containing whitespace-separated tokens representing the "normalized" argument. One then uses a while-loop to parse it natively. getopts is meant to be repeatedly called like the C getopt. When it hits the end of arguments, it returns 1 (shell false).

Enhancements

In various getopts In spring 2004 (Solaris 10 beta development), the libc implementation for getopt() was enhanced to support long options. As a result, this new feature was also available in the built-in command getopts of the Bourne Shell. This is triggered by parenthesized suffixes in the optstring specifying long aliases. KornShell and Zsh both have an extension for long arguments. The former is defined as in Solaris, while the latter is implemented via a separate zparseopts command. KornShell additionally implements optstring extensions for options beginning with + instead of -.

In Linux getopt An alternative to getopts is the Linux enhanced version of getopt, the external command line program. The Linux enhanced version of getopt has the extra safety of getopts plus more advanced features. It supports long option names (e.g. --help) and the options do not have to appear before all the operands (e.g. command operand1 operand2 -a operand3 -b is permitted by the Linux enhanced version of getopt but does not work with getopts). It also supports escaping metacharacters for shells (like tcsh and POSIX sh) and optional arguments.

Comparison

Examples Suppose we are building a Wikipedia downloader in bash that takes three options and zero extra arguments:

wpdown -a article name -l [language] -v

When possible, we allow the following long arguments:

-a --article -l --language, --lang -v --verbose

For clarity, no help text is included, and we assume there is a program that downloads any webpage. In addition, all programs are of the form:

Using old getopt The old getopt does not support optional arguments:

This script will also break with any article title with a space or a shell metacharacter (like ? or *) in it.

Using getopts Getopts give the script the look and feel of the C interface, although in POSIX optional arguments are still absent:

Since we are no longer operating on shell options directly, we no longer need to shift them within the loop. However, a slicing operation is required to remove the parsed options and leave the remaining arguments. It is fairly simple to emulate long option support of flags by treating --fast as an argument fast to an option -. That is, -: is added to the optstring, and - is added as a case for opt, within which OPTARG is evaluated for a match to fast. Supporting long options with an argument is more tedious, but is possible when the options and arguments are delineated by =.

Using Linux getopt Linux getopt escapes its output and an "eval" command is needed to have the shell interpret it. The rest is unchanged:

See also List of Unix commands

References

External links getopts: process command line arguments – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Group

Worked examples

Example 1 — a first encounter with Getopts

Start with the simplest possible case. Write down what Getopts claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Getopts before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Getopts ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Getopts

In research
Getopts appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Getopts in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Getopts is common in secondary-school and first-year university syllabi. It links to neighbouring topics IBM i Qshell commands, Unix SUS2008 utilities, Unix stubs, so understanding it makes those chapters shorter.
In everyday life
Look for Getopts outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Getopts” →

How to study Getopts in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Getopts means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Getopts out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Getopts in simple terms?

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt.

Why does Getopts matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Getopts?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Getopts.

Tags

  • IBM i Qshell commands
  • Unix SUS2008 utilities
  • Unix stubs

Keep exploring