typestar

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

  1. "vn:" declares -v as a flag and -n as taking a value.
  2. $OPTARG carries the value; * catches bad flags.
  3. The while/case pair is the standard shape.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Scripts & safety, step 23 of 26 in Language basics.

← Previous Next →