diff --git a/lib/opt.sh b/lib/opt.sh index 3042760..1ab38a3 100644 --- a/lib/opt.sh +++ b/lib/opt.sh @@ -47,6 +47,17 @@ setargs() { _ARGV_SUBINDEX=1 } +# Gets all the remaining unparsed arguments and saves them to a variable. +# +# Arguments: +# $1 -- The variable to save the args to. +# +# Example: +# getargs remaining_args +getargs() { + eval "$1=($(printf '%q ' "${_ARGV[@]:$_ARGV_INDEX}"))" +} + # Resets the internal _ARGV* variables to the original script arguments. # This is the equivalent of storing the top-level $@ and using setargs with it. resetargs() { diff --git a/test/suite/lib_opt.sh b/test/suite/lib_opt.sh index f0a0eb4..0c0ccd1 100644 --- a/test/suite/lib_opt.sh +++ b/test/suite/lib_opt.sh @@ -397,3 +397,21 @@ test:fn_resetargs() { assert_opt_name "--long-implicit" } + +# shellcheck disable=SC2154 +test:fn_getargs() { + description "Function getargs." + + setargs "--one=two" "three" "--four" + shiftopt + + getargs args + + assert_equal 2 "${#args[@]}" + assert_equal "three" "${args[0]}" + assert_equal "--four" "${args[1]}" + + # Ensure getargs doesn't remove remaining arguments. + shiftopt + assert_opt_name "three" +}