Last Updated: February 25, 2016
· cornwe19

Using getopts in bash functions

Looking to use getopts to help parse the command line args of your bash function? You'll need to make sure to define OPTIND as a local variable or it will be affected by other scripts running in your terminal session.

function myfunc() {
    local OPTIND # Must be local
    while getopts ":ab" opt; do
       case $opt in
       a) echo "using option a";;
       b) echo "using option b";;

Ref. stack overflow answer