From: Matthias Kruk Date: Thu, 11 Aug 2022 13:06:36 +0000 (+0900) Subject: include/opt: Make return values of opt_get() more helpful X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=96f78c851f3eef6ef10fed6e0e3a8d139ca94883;p=toolbox include/opt: Make return values of opt_get() more helpful The function `opt_get()` returns 0 when an option is valid but was not set. This makes it impossible to distinguish if the value of the option is the empty string or it does not have a value at all. Further, it does not return an error if an invalid option's value was requested. This commit fixes the behavior of `opt_get()` so that it returns 0 if an option is valid and has a value (default or user-defined), 1 in case that the option name is invalid, and 2 in case that the option name is valid but it does not have a value. --- diff --git a/include/opt.sh b/include/opt.sh index 5ed8d94..e508575 100644 --- a/include/opt.sh +++ b/include/opt.sh @@ -109,10 +109,13 @@ opt_add_arg() { __opt_desc["$long"]="$desc" __opt_regex["$long"]="$regex" __opt_action["$long"]="$action" - __opt_default["$long"]="$default" __opt_map["-$short"]="$long" __opt_map["--$long"]="$long" + if [[ -n "$default" ]]; then + __opt_default["$long"]="$default" + fi + ((__opt_num++)) return 0 @@ -233,8 +236,12 @@ opt_get() { if array_contains "$long" "${!__opt_value[@]}"; then echo "${__opt_value[$long]}" - else + elif array_contains "$long" "${!__opt_default[@]}"; then echo "${__opt_default[$long]}" + elif [[ -n "${__opt_map[--$long]}" ]]; then + return 2 + else + return 1 fi return 0