Fix the Bash implementation for not ignoring the options specified after arguments.

This was caused by the getopts builtin. Now the regular arguments are processed and removed from the parameter list before getopts is called, so it can parse all of the provided options, regardless of whether they were specified before or after regular arguments.
This commit is contained in:
Renato Silva 2014-09-11 10:22:00 -03:00
parent 3d8b0c3e15
commit d4448390c3
1 changed files with 26 additions and 18 deletions

View File

@ -115,6 +115,32 @@ parse_options() {
fi
done
# Extract regular arguments
index=1
parameters=()
for argument in "$@"; do
if [[ "$argument" = -* ]]; then
parameters+=("$argument")
for known_option in "${options[@]}"; do
known_option_var=${known_option#*=}
known_option_name=${known_option%=$known_option_var}
if [[ "$known_option_var" = "?" && "$argument" = --$known_option_name ]]; then
next_is_value="yes"
break
fi
done
else
if [[ -z "$next_is_value" ]]; then
arguments+=("${!index}")
else
parameters+=("$argument")
fi
next_is_value=""
fi
index=$((index + 1))
done
set -- "${parameters[@]}"
# Parse the provided options
while getopts ":${short_options}-:" option; do
option="${option}${OPTARG}"
@ -181,24 +207,6 @@ parse_options() {
exit
fi
done
# Detect regular arguments
for argument in "$@"; do
if [[ "$argument" = -* ]]; then
for known_option in "${options[@]}"; do
known_option_var=${known_option#*=}
known_option_name=${known_option%=$known_option_var}
if [[ "$known_option_var" = "?" && "$argument" = --$known_option_name ]]; then
next_is_value="yes"
break
fi
done
else
[[ -z "$next_is_value" ]] && arguments+=("$1")
next_is_value=""
fi
shift
done
}
parse_options "$@"