Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 4: Advanced Shell Scripting Commands | ||
|
This command is used to check valid command line argument are passed to script. Usually used in while loop.
Syntax:
getopts {optsring} {variable1}
getopts is used by shell to parse command line argument.
As defined in man pages:
"optstring contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. Each time it is invoked, getopts places the next option in the shell variable variable1, When an option requires an argument, getopts places that argument into the variable OPTARG. On errors getopts diagnostic messages are printed when illegal options or missing option arguments are encountered. If an illegal option is seen, getopts places ? into variable1."
Examlpe:
We have script called ani which has syntax as
ani -n -a -s -w -d
Options: These are optional argument
-n name of animal
-a age of animal
-s sex of animal
-w weight of animal
-d demo values (if any of the above options are used their values are not taken)
Above ani script is as follows:
$ vi ani |
Save it and run as follows
$ chmod +x ani
$ ani -n Lassie -a 4 -s Female -w 20Kg
$ ani -a 4 -s Female -n Lassie -w 20Kg
$ ani -n Lassie -s Female -w 20Kg -a 4
$ ani -w 20Kg -s Female -n Lassie -a 4
$ ani -w 20Kg -s Female
$ ani -n Lassie -a 4
$ ani -n Lassie
$ ani -a 2
See because of getopts, we can pass command line argument in different style. Following are invalid options for ani script
$ ani -nLassie -a4 -sFemal -w20Kg
No space between option and their value.
$ ani -nLassie-a4-sFemal-w20Kg
$ ani -n Lassie -a 4 -s Female -w 20Kg -c Mammal
-c is not one of the valid options.
| ||
The shift command | Essential Utilities for Power User |