Using getopts
We’ll begin with the getopts-demo1.sh script, which is the world’s simplest getopts script. Here’s how it looks:
#!/bin/bash
while getopts ab options; do
case $options in
a) echo "You chose Option A";;
b) echo "You chose Option B";;
esac
done
We’re using a while loop to pass the chosen option or options into a case statement. The ab after the getopts command means that we’re defining a and b as options that we can choose. (This list of allowable options is referred to as the optstring.) You can use any alpha-numeric character as an option. It’s possible to use certain other characters as well, but it’s not recommended. For reasons that will become clear later, you definitely cannot use either a ? or a : as an option. After the ab, you see options, which is just the name of the variable that we’ll use in the case construct. (You can name...