From d4448390c32f6e51de3a24a67c3aa55081af1c92 Mon Sep 17 00:00:00 2001 From: Renato Silva Date: Thu, 11 Sep 2014 10:22:00 -0300 Subject: [PATCH] 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. --- easyoptions.sh | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/easyoptions.sh b/easyoptions.sh index 3cdea9e..1e45fcf 100644 --- a/easyoptions.sh +++ b/easyoptions.sh @@ -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 "$@"