Functions and Scripts
Getopts
Parsing Flags
getopts reads short command-line flags one at a time. Scripts use it to turn options into named variables.
Program
Play the script to watch -v -t docs update verbose and target.
getopts.sh
#!/usr/bin/env bash
set -- -v -t docs
verbose=false
target="build"
while getopts "vt:" opt; do
case "$opt" in
v) verbose=true ;;
t) target="$OPTARG" ;;
esac
done
echo "$verbose:$target"
getopts
`getopts` parses short flags such as `-v` and options with values such as `-t docs`.
OPTARG
`OPTARG` holds the value attached to the current option.