views:

1030

answers:

2

Can you use the bash "getopts" function twice in the same script?

I have a set of options that would mean different things depending on the value of a specific option. Since I can't guarantee that getopts will evaluate that specific option first, I would like to run getopts one time, using only that specific option, then run it a second time using the other options.

+4  A: 

Yes, just reset OPTIND afterwards.

#!/bin/bash

set -- -1
while getopts 1 opt; do
    case "${opt}" in
        1) echo "Worked!";;
        *) exit 1;
    esac
done

OPTIND=1
set -- -2
while getopts 2 opt; do
    case "${opt}" in
        2) echo "Worked!";;
        *) exit 1;
    esac
done
andrew
Sadly, this demonstrates mainly that `set -- ...` is destructive. To show that getopts is non-destructive, you would have the second use look for option 1 again (and omit the second `set --` statement). Alternatively, you'd echo "$@" after each loop.
Jonathan Leffler
A: 

getopts does not modify the original arguments, as opposed to the older getopt standalone executable. You can use the bash built-in getopts over and over without modifying your original input.

See the bash man page for more info.

HTH.

cheers,

Rob

Rob Wells