getopts with non-option arguments?

Hello everyone,

Is it possible to use getopts and also receive arguments without option flags?

e.g. myscript arg1 arg2 -a arg3 -b arg4

If so, how do you stop getopts from exiting as soon as it detects the non-option arguments?

Yes, but as myscript -a arg3 -b arg4 arg1 arg2. man getopts for further information

Save and remove the leading arguments before calling getopts, e.g.:


n=1
while [ $# -gt 0 ]
do
  case $1 in
    -*) break;;
    *) eval "arg_$n=\$1"; n=$(( $n + 1 )) ;;
  esac
  shift
done

while getopts abc opt
do
  case $opt in
    a|b|c) echo opt $opt ;;
  esac
done