#!/bin/sh -
# Beware variables can be inherited from the environment. So
# it's important to start with a clean slate if you're going to
# dereference variables while not being guaranteed that they'll
# be assigned to:
unset -v file arg1 arg2
# no need to initialise OPTIND here as it's the first and only
# use of getopts in this script and sh should already guarantee it's
# initialised.
while getopts a:b:i: option
do
case "${option}" in
(a) arg1=${OPTARG};;
(b) arg2=${OPTARG};;
(i) file=${OPTARG};;
(*) exit 1;;
esac
done
shift "$((OPTIND - 1))"
# now "$@" contains the rest of the arguments
if [ -z "${file+set}" ]; then
if [ "$#" -eq 0 ]; then
echo >&2 "No input file specified"
exit 1
else
file=$1 # first non-option argument
shift
fi
fi
if [ "$#" -gt 0 ]; then
echo There are more arguments:
printf ' - "%s"\n' "$@"
fi
I changed the bash to sh as there's nothing bash-specific in that code.