Home > Mobile >  How do I check if an associative array exists in Bash >=5.2?
How do I check if an associative array exists in Bash >=5.2?

Time:10-14

In bash 5.1 I can use -v to check if an associative array exists:

bash-5.1# declare -A a
bash-5.1# a[foo]=bar
bash-5.1# [[ -v a[@] ]]; echo $?
0

But after upgrading to bash 5.2, I can no longer do this:

bash-5.2# declare -A a
bash-5.2# a[foo]=bar
bash-5.2# [[ -v a[@] ]]; echo $?
1

This change has broken most of my scripts, but I cannot figure out a way to get this functionality back.

Edit: Please see discussion of this change: https://lists.gnu.org/archive/html/bug-bash/2021-04/msg00058.html

tl;dr test -v now treats '@' as a literal key when used with an associative array

CodePudding user response:

To test whether a variable named foo is declared as an associative array:

[[ ${foo@a} = A ]]

The a parameter transformation is described in the Shell Parameter Expansion section of the manual (scroll all the way down).

And to test if it is not empty:

[[ ${#foo[@]} -gt 0 ]]
  •  Tags:  
  • bash
  • Related