getopts is a nice way to get simple arguments, rather than having to write your own code to get them.
Let’s start with an example.
match=0 dev=0 verbose=0 file= while getopts mdvf: arg do case $name in m) match=1 ;; d) dev=1 ;; v) verbose=1 ;; f) file="$OPTARG" ;; ?) printf "Usage: %s: [-m] [-dv] [-f file]\n" $0 exit 1 ;; *) echo "An incorrect argument was specified" ;; esac done
In here we have set our default values for
dev. We have then our
while getopts argument where we specify the arguments that will be accepted (where you see
: after the
f means that one gets an argument, in this case the file name. The option for the argument is obtained in the
$OPTARG variable within the
Speaking of which, list all of the arguments in the
case section. There are two special arguments:
?means nothing was given. Useful for giving the usage explanation.
*means an unknown argument was given.
For more information, see: