Named parameters not working in shell function

72 views Asked by At

I have this shell script that is supposed to accept two optional parameters start and end from command line:

function foo {
    # -s : start
    # -e : end
    while getopts 's:e:' arg
    do
        case ${arg} in
            s) start=${OPTARG};;
            e) end=${OPTARG};;
            *) return 1 # illegal option
        esac
    done

    echo "start, end:"
    echo $start, $end

    unset start
    unset end
}

I get random results from the runs. Here is a list of runs (in chronological order), and their outputs:

1.

$ foo
start, end:
,

2.

$ foo -s 2011
start, end:
2011,

3.

$ foo -e 2015
start, end:
,

4.

$ foo -s 2011 -e 2016
start, end:
, 2016

5.

$ foo -s 2011 -e 2016
start, end:
,

6.

$ foo
start, end:
,

7.

$ foo -s 2011 -e 2016
start, end:
2011, 2016

8.

$ foo -s 2011 -e 2016
start, end:
,

Please help. The requirement is as simple as the first two lines of this post. Any alternative method works too, but I would love to know what I'm doing wrong here. TIA.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Your function sets global variable OPTIND due to invocation of getopts. You can prevent this by adding local OPTIND at the beginning of your function (you might want to do that for variables end and start as well).