Add Options to shell scripts

Getopts is an easy way to add nice options to a shell script:

#!/bin/bash

while getopts ":ab:" opt; do
  case $opt in
    a)
      echo "-a was triggered!" >&2
      ;;
    b) 
      echo "switch -b activated with: $OPTARG"
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

The while loop iterates over the return values of getopts, if you place a colon “:” after a option this option will recieve an argument.

References