help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to test if a variable exists and is a hash?


From: Peng Yu
Subject: Re: How to test if a variable exists and is a hash?
Date: Sat, 11 Jul 2020 17:33:49 -0500

On 7/11/20, Koichi Murase <myoga.murase@gmail.com> wrote:
> 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* ]]

I am not familar with the usage of ${x@a}. Where is it documented? Thanks.

>
> 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
>


-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]