6 ms·
Am I the only one who finds argbash unnecessarily complicated? For my own needs, I rely on a tiny function I wrote, called process_optargs. Example use: sou
by tpoacher 4y ago
Am I the only one who finds argbash unnecessarily complicated?
For my own needs, I rely on a tiny function I wrote, called process_optargs. Example use:
source /path/to/process_optargs
source /path/to/error
source /path/to/is_in
function myfunction () { # example function whose options/arguments we'd want to process
# Define local variables which will be populated or checked against inside process_optargs
local -A OPTIONS=()
local -a ARGS=()
local -a VALID_FLAG_OPTIONS=( -h/--help -v --version ) # note -v and --version represent separate flags here! (e.g. '-v' could be for 'verbose')
local -a VALID_KEYVAL_OPTIONS=( -r/--repetitions )
local COMMAND_NAME="myfunction"
# Process options and arguments; exit if an error occurs
process_optargs "$@" || exit 1
# Validate and collect parsed options and arguments as desired
if is_in '-h' "${!OPTIONS[@]}" || is_in '--help' "${!OPTIONS[@]}"
then display_help
fi
if is_in '-r' "${!OPTIONS[@]}"; then REPS="${OPTIONS[-r]}"
elif is_in '--repetitions' "${!OPTIONS[@]}"; then REPS="${OPTIONS[--repetitions]}"
fi
if test "${#ARGS[@]}" -lt 2
then error "myfunction requires at least 2 non-option arguments"
exit 1
fi
# ...etc
}
It works as you'd expect, with appropriate checks for correctness of inputs, and is compatible with most unix conventions (including '--' and '-' as arguments).
If anyone's interested let me know and I can share the code.