I downloaded a script the other day and I was immediately drawn to a new bash function (to me), getopts. It was so clean, clear and concise that I immediately wanted to start using it in my bash scripts.

First of all, what is getopts? Here’s the function definition:

getopts string name [args]

getopts processes command line arguments in a bash script using a while loop. Here’s an example:

#!/bin/bash
#
# Usage: 
#   this-script.sh -a alpha -b bravo
#
# Output:
#   Option A=alpha and Option B=bravo
#

while getopts a:b: options; do
    case $options in
        a ) a=$OPTARG;;
        b ) b=$OPTARG;;
        * ) echo "Invalid option: -$OPTARG" >&2; exit 1;;
        esac
    done

echo "Option A=$a and Option B=$b"

For more info, have a look at this article.

JohnBiz.net

Technophile and outdoor enthusiast