$0 : the program itself
$1 : the first parameter
$2 : the second parameter
A string enclosed in single or double quotes will be passed as a single parameter, and the quotes will be stripped.
$# : the number of total parameters, not including the program itself
$@ : the array of parameters. Double-quoted "$@" is equal to "$1", "$2", "$3".... This is the most common usage. But there are other variations, like $*, "$*", $@, or "$@". They can be explained distinctly. For more detail, see examples here.
For options, using
getopt optstring optname
where optstring is a double-quote string of option letters, like ":p:q". A colon (:) after an option letter indicates that the option
requires a value; The leading colon tells getopts to be silent and suppress the
normal error messages.
The second parameter,
optname, is the name of a variable which will receive the name of the option found. If an option is expected to have a value, the value, if present, will be placed in the variable OPTARG. In silent mode, either of the following two error conditions may occur.
- If an unrecognized option is found, then optname will contain a ? and OPTARG will contain the unknown option.
- If an options that requires a value is found but the value is not, then optname will contain a : and OPTARG will contain the name of the option whose argument is missing.
For example, getopt ":p:q" optnames
will require an option (-p) with value, and -q without having value.
echo "OPTIND starts at $OPTIND"
while getopts ":pq:" optname
case "$optname" in
echo "Option $optname is specified, with value"
echo "Option $optname has value $OPTARG"
echo "Unknown option $OPTARG"
echo "No argument value for option $OPTARG"
# Should not occur
echo "Unknown error while processing options"
echo "OPTIND is now $OPTIND"