Is mixing getopts with positional parameters possible?

I wanted to do something similar to the OP, and I found the relevant information I required here and here

Essentially if you want to do something like:

script.sh [options] ARG1 ARG2

Then get your options like this:

while getopts "h:u:p:d:" flag; do
case "$flag" in
    h) HOSTNAME=$OPTARG;;
    u) USERNAME=$OPTARG;;
    p) PASSWORD=$OPTARG;;
    d) DATABASE=$OPTARG;;
esac
done

And then you can get your positional arguments like this:

ARG1=${@:$OPTIND:1}
ARG2=${@:$OPTIND+1:1}

More information and details are available through the link above.

Hope that helps!!

Leave a Comment