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
Replay: real traced execution (multi-file project)
#!/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"
$@ ← -v -t docs
3set -- -v -t docs4verbose=falsevalues this step-v -t docs$@verbose ← false
3set -- -v -t docs4verbose=false5target="build"values this stepfalseverbosetarget ← build
4verbose=false5target="build"6while getopts "vt:" opt; dovalues this stepbuildtargetopt ← v, OPTIND ← 2
5target="build"6while getopts "vt:" opt; do7 case "$opt" invalues this stepvopt2OPTINDverbose ← true
7case "$opt" in8 v) verbose=true ;;9 t) target="$OPTARG" ;;values this steptrueverboseopt ← t, OPTARG ← docs, OPTIND ← 4
5target="build"6while getopts "vt:" opt; do7 case "$opt" invalues this steptoptdocsOPTARG4OPTINDtarget ← docs
8 v) verbose=true ;;9 t) target="$OPTARG" ;;10esacvalues this stepdocstargetdocsOPTARGecho "$verbose:$target"
11done12echo "$verbose:$target"outputtrue:docsvalues this steptrueverbosedocstarget
Follow the Flags
set -- -v -t docsmakes the script arguments-v -t docs.verbosestarts asfalse, andtargetstarts asbuild.- First
getoptsseesopt=vwithOPTIND=2, soverbosebecomestrue. - Second
getoptsseesopt=t,OPTARG=docs, andOPTIND=4, sotargetbecomesdocs. - The script prints
true:docs. | pass | opt | OPTARG | OPTIND | result | | --- | --- | --- | --- | --- | | start | - | - | - |verbose=false,target=build| | 1 |v| - | 2 |verbose=true| | 2 |t|docs| 4 |target=docs| | stdout | - | - | - |true:docs|
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.
Exercise: getopts.sh
Reproduce true:docs, then identify which option changes verbose and which option changes target.