using associative arrays with zparseopts

Viewed 306

I'm trying to use an associate array to parse options with zparseopts.

I have some working code, shared below, using normal arrays...but it's so awkward and verbose. i want to just ask if -f is present using opts as an associative array, by passing -A as my option to zparseopts, but I can't seem to make it work.

local -a opts
zparseopts -D -a opts f
if [[ ${opts[(ie)-f]} -le ${#opts} ]]; then
  echo "force was passed"
else
  echo "be kind"
fi

thanks for any help!

1 Answers

When the (i) subscript flag is used with an associative array, the substitution will return the key if a match was found, or an empty value if it was not. So you just need to test for a non-empty string:

local -A opts
zparseopts -D -A opts f
if [[ -n ${opts[(ie)-f]} ]]; then
  echo "force was passed"
else
  echo "be kind"
fi

To consolidate option parsing, I've used this (slightly cryptic) substitution:

flag=-f; force=${${:-true false}[(w)((${#opts[(i)$flag]}>0?1:2))]}
flag=-q; quiet=${${:-true false}[(w)((${#opts[(i)$flag]}>0?1:2))]}

...

if $force; then
    ...

if ! $quiet; then
    ...
Related