anon_stackoverflock
anon_stackoverflock

Reputation: 113

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

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

Upvotes: 2

Views: 189

Answers (1)

oguz ismail
oguz ismail

Reputation: 50775

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

Upvotes: 4

Related Questions