Getopts

From LQWiki
Jump to: navigation, search

Getopts parses a parameters string and stores it in a normalized format. Imagine you want to write your own bash script foo that takes Command options. It should be no matter if the user calls it

foo -abcd

or

foo -a -b -c -d

getopts normalizes these parameters:

scorpio:~ # getopts abcd myvar -abcd
scorpio:~ # echo $myvar
a

The first parameter tells getopt which options are allowed (a,b,c and d in this case), the second parameter is the variable name that gets the values from the parameter list. The rest is the string to be normalized.

See also