Bash -v test doesn’t work with associative arrays in 4.3.46

associative arraybashset

The -v unary operator that was introduced in version 4.2 to test if a variable is set or not does not appear to work in bash 4.3.46 on associative arrays.

I have some bash test code that I run against a set of bash functions, and they all pass in bash 4.2 (on CentOS 7.1). I recently booted up a Lubuntu 16.04.1 distro and noticed a good portion of my tests now failed, with bash 4.3.46. It seems like all of the failures are due to code like this:

function is_var_set {
    local var="${1:?"No var provided to 'is_var_set'!"}"
    [[ -v "$var" ]]
}

declare -A array=(["a"]="element 1")
is_var_set "array"

Is this a widely known thing/was support removed for associative arrays?

Best Answer

The current bash manual on arrays says

An array variable is considered set if a subscript has been assigned a value.

So IMHO, you would have to do something different for associative arrays. I can't tell if this is a recent change in bash behavior.

Another way to define is_var_set would be to (ab)use the declare builtin, using the following:

The return status is zero unless ... one of the names is not a valid shell variable name ...

function is_var_set {
  declare -p "${1:?"No var provided to 'is_var_set'! "}" >& /dev/null
}

The above would work for top-level variable names, but not for any particular array elements.

Related Question