bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: bash can't distinguish between empty and unset arrays


From: Chet Ramey
Subject: Re: bash can't distinguish between empty and unset arrays
Date: Fri, 5 Feb 2016 14:28:45 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Thunderbird/38.5.1

On 2/3/16 6:43 PM, Martijn Dekker wrote:
> bash treats an empty array as if it were an unset variable, which seems
> very illogical as empty is quite distinct from unset:
> 
> $ myarray=()
> $ [[ -v myarray ]] && echo set || echo unset
> unset

If you use the name of an array in a variable context without using a
subscript, it's equivalent to referencing element 0.

Bash considers a variable set if it has been assigned a value.  For an
array, being set means that the number of elements is greater than zero.

> $ set | grep ^myarray=        # yet, it's set:
> myarray=()

Yes, this is arguably a bug.  Bash tries to output the set of shell
variables in a way that will restore them if the output is evaluated,
but only puts array variables in the `set' output.  It doesn't do that
for variables that have been assigned attributes but not values; such
variables are lost.

> $ set -u
> $ for i in "address@hidden"; do :; done
> bash: address@hidden: unbound variable

None of the elements have been assigned a value.

> Note also that the "unbound variable" error is inconsistent with the
> behaviour of "$@"; I would have thought that, logically, "$@" and
> "address@hidden" should behave the same way, since arrays are implemented as a
> logical extension of the positional parameters concept.

$@ and $* receive a special carve-out in Posix; they are the only
exceptions to set -u.

-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU    address@hidden    http://cnswww.cns.cwru.edu/~chet/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]