Bash: Detect if variable is an array

From FVue
Jump to: navigation, search

Problem

I want to detect if a variable is an array. How can I do so?

Solution

Use the following expression to determine if a bash variable is an array:

declare -p variable-name 2> /dev/null | grep -q 'declare \-a'

Examples:

$ v=(foo bar)  # v is an array
$ declare -p v | grep -q '^declare \-a' && echo array || echo no array
array
$ v='declare -a'  # v is a string
$ declare -p v | grep -q '^declare \-a' && echo array || echo no array
no array
$ declare -p non-existing-var | grep -q '^declare \-a' && echo array || echo no array
bash: declare: non-existing-var: not found
no array
$     # The `2> dev/null' protects against the `declare: not found' error message above
$ declare -p non-existing-var 2> /dev/null | grep -q '^declare \-a' && echo array || echo no array
no array

Comments

blog comments powered by Disqus