The input to my shell should follow the following signature.
myscript.sh var1 var2 [-o var3] [-r var4].
The -o and -r are optional inputs and these options can occur at any location (between var1 & var 2 or at the start/end) but var3 will always preceed var4 if var 3 is specified. Also var1 will preceed var 2.
#!/bin/bash
case "$#" in
([01]) echo "Usage: $0 var1 var2 [-o val3] [-r val4]" >&2; exit 1;;
esac
VAR1="$1"
VAR2="$2"
VAR3=
VAR4=
while getopts ":o:r:" opt; do
case $opt in
o)
VAR3=$OPTARG
;;
r)
VAR4=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
shift $(( OPTIND - 1 ))
if [ -z "${VAR3+xxx}" ] && [ -z "${VAR4+xxx}" ];
then
echo $1 $2;
elif [ -z "${VAR3+xxx}" ];
then
echo $1 $2 $VAR4;
elif [ -z "${VAR4+xxx}" ];
then
echo $1 $2 $VAR3;
else
echo $1 $2 $VAR3 $VAR4;
fi
How to handle the case where the optional arguments are inbetwen var1 & var2