Last Updated: February 25, 2016
·
5.303K
· 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";;
       esac
    done
}

Ref. stack overflow answer http://stackoverflow.com/a/16655341/423941