My typical setup for parsing command-line options is:
CONF=""
INPUT=""
while getopts ":c:i:" FLAG; do
case $FLAG in
i) INPUT=$OPTARG;;
c) CONF=$OPTARG;;
\?) echo -e "\nInvalid option: -$OPTARG"
usage;;
:) echo -e "Option -$OPTARG requires an argument."
usage;;
esac
done
if [ "$#" -eq 0 ]; then
usage
fi
I'm looking for a way to catch when a valid flag is provided but no argument is - for example:
./Script.sh -c -i
Returns usage
. I was under the impression that this line:
:) echo -e "Option -$OPTARG requires an argument."
Handled this however when running the script as above using flags without arguments, the usage function is not firing nor is the echo.
What am I doing wrong?
If you invoke your script with either ./script.sh -c -i -c
or ./script.sh -c
, both will show the error message Option -c requires an argument.
However, when invoking ./script.sh -c -i
, you are passing value "-i" for the -c
argument, so that at the end of arguments parsing, you end up with CONF=-c
and INPUT not set
.