As you've found, getopts
stops at the first non-option word. You're forced to iterate over all the arguments:
dir="some default"
recursive=false
for arg; do
if [[ $arg == "-r" ]]; then
recursive=true
else
dir=$arg
fi
done
An advantage to using "true" and "false" like this is you can then write this, since true
and false
are programs on the $PATH:
if $recursive; then
do_something_repeatedly
else
do_something_once
fi
Checking for invalid options:
for arg; do
case $arg in
-r) recursive=true ;;
-*) echo "invalid option: $arg" ;;
*) dir=$arg ;;
esac
done