18

I want to parse some arguments to a bash script using getopts but want to be able to access the remaining args that are not included in the option list. So for example, if I have a call:

% script -a -b param -c param -d other arguments here

I would have:

while getopts "ab:c:d" opt ; do
.
done

What is the easiest way to get "other arguments here", which should be unprocessed by getopts?

Tim
  • 1,879
  • 3
  • 18
  • 16

2 Answers2

20

you need to shift when you parse an arg, or put

shift $((OPTIND -1)) after you have finished parsing, then deal in the usual way e.g.

while getopts "ab:c:d" opt ; do
.
done
shift $(expr $OPTIND - 1 )

while test $# -gt 0; do
  echo $1
  shift
done
phihag
  • 232
  • 1
  • 11
pogma
  • 241
  • 2
  • 2
  • 1
    It's worth explaining, that $OPTIND is the index of the next option to be considered, after each getopts is run. Hence is $* contains 3 parameters, following the first valid call it's 2, and the second it's 3. Should the a call be invalid, it'll drop out with the earlier value. So if parameter 1 isn't valid, OPTIND will be 1 (hence the above example will `shift $(expr 1 - 1)` which is safe. – sibaz Oct 30 '17 at 10:03
1

At the end of the parsing, once you have shifted the variable $@ contains the end of the line :

while getopts "ab:c:d" opt ; do
.
done
shift $((OPTIND-1))
OTHERARGS=$@
Bruno Mairlot
  • 421
  • 3
  • 5