1

In Bash test if associative array is declared

I want to test a variable is declared as an associative array or not. I see the above discussion. But it is not clear which one is the best.

The following mentioned on the above link, but does not work.

declare -A x; [[ -v x[@] ]]; echo "$?"

This is costly. It has to print the whole data structure. It can be slow when the data is large.

[[ "$(declare -p FOO 2>/dev/null)" == "declare -A"* ]]

What is the best way to check whether a variable is an associative array?

EDIT: The answer below is the best for Bash 5. The results on the link at the top of the message are obsolete and those methods should be ignored for Bash 5.

4
  • Please add your (useful!) answer to the preexisting question. Commented Apr 1, 2021 at 0:15
  • No. That is a very bad idea. Commented Apr 1, 2021 at 0:20
  • 1
    How so? The point of merging questions is to get more attention -- right now, people who see the existing question won't be able to find your answer. Commented Apr 1, 2021 at 0:26
  • Because the existing question has more eyes (more views, more presence in search engine indices -- and is already the target of other duplicate flags), if you don't move your answer, I'll build my own version of it there -- but it would be better for you to get the credit yourself, since you did the research. Commented Apr 1, 2021 at 0:33

1 Answer 1

5

The following can be used to test whether a bash variable is an associative array.

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

${x@a} can be used to test whether it is a variable and an array as well.

$ declare x; echo "${x@a}"

$ declare -a y; echo "${y@a}"
a
$ declare -A z; echo "${z@a}"
A
Sign up to request clarification or add additional context in comments.

18 Comments

Am I correct to believe that this is a bash 5.0 feature, and not portable back to 3.x or 4.x series?
I am not sure how early it goes back to. I only have bash 5 to test.
To be clear, I'm pretty sure you could add this as a new answer to the existing question (to be extending it to cover newer bash versions than the existing answers were written for).
...the @<anything> suffix expansions were mostly added in 5.0, as a group.
I don't think it is a good idea to merge with the old thread. No answers of there are of practical use. It is too bad to show both bad answers and good answers. The old bad answers should be just ignored. This questions should not be closed.
|