getopts in Bash
Flag parsing the built-in way.
usage() { echo "usage: demo [-v] [-n name]"; }
verbose=0
name="world"
while getopts "vn:" opt; do
case $opt in
v) verbose=1 ;;
n) name=$OPTARG ;;
*) usage; exit 1 ;;
esac
done
(( verbose )) && echo "verbose mode on"
echo "hello, $name"
How it works
"vn:"declares-vas a flag and-nas taking a value.$OPTARGcarries the value;*catches bad flags.- The while/case pair is the standard shape.
Keywords and builtins used here
casedodoneechoesacexitgetoptsinwhile
The run, in numbers
- Lines
- 14
- Characters to type
- 237
- Tokens
- 60
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 45 seconds.
Step 2 of 3 in Scripts & safety, step 23 of 26 in Language basics.