In Bash test if associative array is declared

In bash 4.2 or later, you can use the -v option:

[[ -v FOO[@] ]] && echo "FOO set"

Note that in any version, using

declare -A FOO

doesn’t actually create an associative array immediately; it just sets an attribute on the name FOO which allows you to assign to the name as an associative array. The array itself doesn’t exist until the first assignment.

Leave a Comment