3

Both a positional parameter ($1, $2, and so forth) and an option (and/or argument) are written directly after a command, so what is the definition or phrasing to explain how to distinct them?

In other words, how to formally explain the difference between a positional parameter and an option (and/or argument)?

13

An option (also commonly called "flag" or "switch") is one type of command line argument. A command line argument is a single word (or quoted string) present on the command line of a utility or shell function.

Upon calling a shell script or shell function with a certain number of arguments, each individual argument will be available as a positional parameter inside the script or function.

Terminology:

An "argument" can be

  • an "option" (like -a, but only if the utility recognises it as an option),
  • an "option-argument" (like foo in -a foo if -a is an option that takes an argument), or
  • an "operand" (a non-option argument that is also not an option-argument, for example foo in -a foo if -a does not take an option-argument).

Real example of all of the above (using GNU mv):

mv -t targetdir -f file1 file2
  • Arguments: -t, targetdir, -f, file1, and file2
  • Options: -t and -f
  • Option-arguments: targetdir
  • Operands: file1 and file2.

From the POSIX definitions:

[An argument is, in] the shell command language, a parameter passed to a utility as the equivalent of a single string in the argv array created by one of the exec functions. An argument is one of the options, option-arguments, or operands following the command name.

[An option is an] argument to a command that is generally used to specify changes in the utility's default behavior.

[An option-argument is a] parameter that follows certain options. In some cases an option-argument is included within the same argument string as the option-in most cases it is the next argument.

[An operand is an] argument to a command that is generally used as an object supplying information to a utility necessary to complete its processing. Operands generally follow the options in a command line.

The positional parameters in a shell script or shell function will be the arguments given on the script's or function's command line, regardless of whether the arguments are options, option-arguments or operands.

The positional parameters may also be set using

set -- something "something else" bumblebees

This sets $1, $2 and $3 to the three strings and clears any other positional parameters.

In this case, the positional parameters no longer have any relation to the arguments passed on the utility's command line.

See also:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy