Session and utilities
The getopts command
Walks through a script's options (-a, -b value) one at a time.
Copy-ready examples
$ set -- -a -b valor && while getopts "ab:" o; do echo "opcion $o ${OPTARG:-sin valor}"; donewalks through two options: -b takes a value and -a does not.Example output
opcion a sin valor opcion b valor
$ set -- -a -b valor pendiente && while getopts "ab:" o; do :; done; shift $((OPTIND - 1)); echo $1when it ends, OPTIND shows where the loose arguments start.Example output
pendiente
$ printf 'while getopts "ab:" o; do echo "opcion $o: ${OPTARG:-sin valor}"; done\n' > p.sh && bash p.sh -a -b valorthe same loop inside a script that receives the options.Example output
opcion a: sin valor opcion b: valor
You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| bash: illegal option -- z | The option -z is not in the option string. Inside a script, the prefix is the script name. | Add the letter to the string, for example "abz", or pass only options that exist. |
| bash: option requires an argument -- b | Option b needs a value and there is none after it. | Pass the value right after it: -b value. |
Typical mistakes
- OPTIND is not reset on its own: if you call getopts again with other arguments in the same shell, set OPTIND=1 first.
- A colon after a letter (b:) means that option takes a value. The colon and the question mark cannot be option letters.
- getopts only works with single letters: for long options such as --file, use getopt.
Differences from similar commands
getopt: is an external program that also accepts long options, such as --file. getopts is built into the shell and only works with letters.- shift: removes arguments from the list. getopts does not remove them: it advances OPTIND, and to discard the options already read you combine it with shift.
FAQ
How do I know there are no options left?
getopts returns a code greater than zero and the variable gets ?. OPTIND holds the index of the first argument that is not an option.
Where is the value of an option?
In the variable OPTARG, which getopts fills when the letter is followed by a colon in the string.
Can I use long options with getopts?
No: it only recognizes letters. For --file or --help use getopt, from the util-linux package, which does support them.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course