How do I check if variable is an array?

Since bash 4.3 it is not that easy anymore.

With "declare -n" you can add a reference to another variable and you can do this over and over again. As if this was not complicated enough, with "declare -p", you do not get the type or the original variable.

Example:

$ declare -a test=( a b c d e)
$ declare -n mytest=test
$ declare -n newtest=mytest
$ declare -p newtest
declare -n newtest="mytest"
$ declare -p mytest
declare -n mytest="test"

Therefore you have to loop through all the references. In bash-only this would look like this:

vartype() {
    local var=$( declare -p $1 )
    local reg='^declare -n [^=]+=\"([^\"]+)\"$'
    while [[ $var =~ $reg ]]; do
            var=$( declare -p ${BASH_REMATCH[1]} )
    done

    case "${var#declare -}" in
    a*)
            echo "ARRAY"
            ;;
    A*)
            echo "HASH"
            ;;
    i*)
            echo "INT"
            ;;
    x*)
            echo "EXPORT"
            ;;
    *)
            echo "OTHER"
            ;;
    esac
}

With the above example:

$ vartype newtest
ARRAY

To check for array, you can modify the code or use it with grep:

vartype $varname | grep -q "ARRAY"

To avoid a call to grep, you could use:

if [[ "$(declare -p variable_name)" =~ "declare -a" ]]; then
    echo array
else
    echo no array
fi

According to this wiki page, you can use this command:

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

Tags:

Arrays

Bash