getopts is a Bourne/POSIX shell builtin for parsing command-line options, available in ash, bash, dash, ksh, zsh, ... on Linux and other Unix systems.
getopts
is a shell builtin for parsing command-line options of the form -a
where a
is a letter or other character. It is available in all Bourne-style shells (Bourne, ash, bash, dash, ksh, zsh, ...) and defined by the POSIX standard.
Using getopts
usually involves using a loop calling getopts OPTSTRING varname
, in which each call to getopts will parse the next option, set varname
with the option name and return success.
Example
#!/bin/sh
while getopts a:b flag
do
case $flag in
a) echo "a flag used, with value $OPTARG" ;;
b) echo "b flag used" ;;
?) echo "Usage: PROGRAM [-a ARG1] [-b]"; exit 1 ;;
esac
done
shift $((OPTIND - 1)) # remove parsed args from the arglist
echo remaining args: $*