$ 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
Cited from http://www.fvue.nl/wiki/Bash:_Detect_if_variable_is_an_array
No comments:
Post a Comment