[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: test_v doesn't work for associative arrays
From: |
Greg Wooledge |
Subject: |
Re: test_v doesn't work for associative arrays |
Date: |
Fri, 10 Jun 2016 10:43:08 -0400 |
User-agent: |
Mutt/1.4.2.3i |
On Fri, Jun 10, 2016 at 02:53:23PM +0200, pskocik@gmail.com wrote:
> declare var
> declare -a ary
> declare -A asoc
>
> var=1
> ary=(1)
> asoc[a]=1
>
> for a in var ary asoc; do
> printf '%s\t' "$a"
> if test -v "$a"; then
...
With arrays, remember that "foo" is the same as "foo[0]" in all contexts.
When you do your test -v on an array's name, you are really doing it on
the array element with index [0].
imadev:~$ unset a
imadev:~$ declare -A a
imadev:~$ a[foo]=bar
imadev:~$ test -v a; echo $?
1
imadev:~$ test -v 'a[foo]'; echo $?
0
imadev:~$ test -v 'a[qz]'; echo $?
1
imadev:~$ unset a
imadev:~$ a[17]=foo
imadev:~$ test -v a; echo $?
1
imadev:~$ test -v 'a[17]'; echo $?
0
imadev:~$ test -v 'a[1]'; echo $?
1
Your script gave you a slightly misleading result because with your
indexed array, element [0] existed: you initialized the array so that
element [0] had the value 1. But your associative array was initialized
so that only element [a] existed.