test -v with array elements

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

test -v with array elements

Luiz Angelo Daros de Luca
Hello,

While using test -v, I noticed that it returns false when I use it
with a sparse or empty array. I need to add [@] or [index] to have it
return true.

Is this expected? If so, it is not documented. It only has:

"True if the shell variable varname is set (has been assigned a value)."

I'm using GNU bash, version 5.0.16(1)-release (x86_64-pc-linux-gnu)

$ A=()
$ test -v A || echo not defined
not defined

Should it?

$ A=(x)
$ test -v A || echo not defined

OK

$ A=()
$ A[1]=1
$ test -v A || echo not defined
not defined

Should it? 'test -v A' is equivalent to 'test -v A[0]'

$ test -v A[1] || echo not defined
$ test -v A[2] || echo not defined
not defined

if index is specified, it would be ok to have it return false. It
would be a better way to test if an array contains a value (other than
variable expansion).

$ test -v A[@] || echo not defined

This only fails when A is an empty array, which might be correct.

Regards,
---
     Luiz Angelo Daros de Luca
            [hidden email]

Reply | Threaded
Open this post in threaded view
|

Re: test -v with array elements

Chet Ramey
On 5/29/20 4:00 PM, Luiz Angelo Daros de Luca wrote:

> Hello,
>
> While using test -v, I noticed that it returns false when I use it
> with a sparse or empty array. I need to add [@] or [index] to have it
> return true.
>
> Is this expected? If so, it is not documented. It only has:
>
> "True if the shell variable varname is set (has been assigned a value)."
>
> I'm using GNU bash, version 5.0.16(1)-release (x86_64-pc-linux-gnu)
>
> $ A=()
> $ test -v A || echo not defined
> not defined
>
> Should it?

Referring to an array without a subscript is equivalent to referencing
element 0.

>
> $ A=(x)
> $ test -v A || echo not defined
>
> OK

This sets A[0]=x

>
> $ A=()
> $ A[1]=1
> $ test -v A || echo not defined
> not defined
>
> Should it? 'test -v A' is equivalent to 'test -v A[0]'

Exactly.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    [hidden email]    http://tiswww.cwru.edu/~chet/