After your while getopts
loop, do this:
shift $((OPTIND-1))
if (( $# > 0 )); then
echo "error: extra args detected: $*" >&2
exit 1
fi
Question
I am writing a script that uses getopts for options that require arguments and some that do not. I want getopts to exit with an error if any switches do not start with a '-', rather than simply stop parsing the options and continue. So if this is my getopts line:
while getopts "a:e:f:o:q:r:djpsvV" opt; do
and I call the script like this:
script.sh -a word -o eat me -j -d -e testing
the script stops parsing at "me" and the remaining switches are ignored. I want it to error out when it reaches "me", because it does not start with a '-'. How do I do that?
Solution
After your while getopts
loop, do this:
shift $((OPTIND-1))
if (( $# > 0 )); then
echo "error: extra args detected: $*" >&2
exit 1
fi