How does `getopts` work? Show a complete example.
IntermediateConceptArguments, I/O, here-docs, process substitution and subshells
Answer
getopts OPTSTRING VAR parses short options one at a time. A letter followed by : takes an argument (in $OPTARG). A leading : in the optstring enables silent mode, where you handle errors yourself: ? for unknown options, : for a missing argument.
env="" verbose=0
while getopts ':e:vh' opt; do
case $opt in
e) env=$OPTARG ;;
v) verbose=1 ;;
h) usage; exit 0 ;;
:) echo "option -$OPTARG requires an argument" >&2; exit 2 ;;
\?) echo "unknown option -$OPTARG" >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1)) # "$@" is now the non-option arguments
[[ -n $env ]] || { echo "-e is required" >&2; exit 2; }
getopts supports bundling (-ve prod) and stops at -- or the first non-option.
More on Arguments, I/O, here-docs, process substitution and subshells
What is the difference between `getopts` and `getopt`?AdvancedExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?IntermediateHow do you send a here-doc to a remote server over SSH, and when should variables expand locally vs remotely?Advanced