Re: How to test if a variable exists and is a hash?
From:
Koichi Murase
Subject:
Re: How to test if a variable exists and is a hash?
Date:
Sun, 12 Jul 2020 04:38:36 +0900
2020-07-12 0:43 Peng Yu <pengyu.ut@gmail.com>:
> What is the best way to check if a variable exists and is a hash? Thanks.
Why don't you use '${x@a}'?
$ declare -A x=()
$ [[ ${x@a} == *A* ]]
If you want to check if x is the associative array with at least one
value, you can use
$ declare -A x=([a]=10)
$ [[ ${x@a} == *A* && -v x[@] ]]
If you want to check if y is declared to be an associative array (but
may not be assigned a value), you can use the fact that the
associative array attribute cannot be cleared by `declare +A':
$ declare -A y
$ ! declare +A y 2>/dev/null
The caveat of `declare +A' approach is that it can only be used for
the current-function-scope variables or global variables (! declare -g
+A y). If you need to test the caller-function-scope variables, you
need to use subshells (though I know that you don't like forks for the
efficiency reason).
$ [[ $(declare -p y 2>/dev/null) == 'declare -A '* ]]
--
Koichi