[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Awkward behavior of empty arrays
From: |
Chet Ramey |
Subject: |
Re: [Help-bash] Awkward behavior of empty arrays |
Date: |
Thu, 31 Aug 2017 10:47:43 -0400 |
User-agent: |
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Thunderbird/52.3.0 |
On 8/31/17 5:51 AM, Andy Chu wrote:
> The problems you point out are indeed subtle, but if you follow a few
> rules, you can avoid them:
>
> 1. Never use anything that isn't in parentheses on the RHS of an array
> initialization.
This is essentially an attempt to avoid the implicit use of subscript 0.
> 2. Never reference an array with anything but "address@hidden" or "${A[i]}"
> where
> i is an integer (double quotes are mandatory in both cases).
>
> Examples 2 and 3 break this rule -- address@hidden doesn't have double quotes.
It's not bad as long as you understand that the difference between
address@hidden
and "address@hidden" is the same as the difference between $@ and "$@". If you
are prepared to deal with the different word splitting behavior, both can
be useful.
>
> also invalid:
> "${A}" # this is an implicit "address@hidden" but is confusing
It's not; it's an implicit "${A[0]}".
> "${A[*]}"
> ${A[*]}
These are useful in the same way that $* and "$*" are useful.
> In particular, don't expect to compare arrays with [[.
>
> $ declare -a A=(A B C D)
> $ declare -a B=('A B' 'C D')
>
> $ echo "address@hidden"
> 4
> $ echo "address@hidden"
> 2
>
> # arrays compare equal because they're coerced to strings before comparison
> $ [[ "address@hidden" == "address@hidden" ]]; echo $?
> 0
Because the operands in [[ commands don't undergo word splitting.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU address@hidden http://cnswww.cns.cwru.edu/~chet/
Re: [Help-bash] Awkward behavior of empty arrays, Chet Ramey, 2017/08/31
Re: [Help-bash] Awkward behavior of empty arrays, Chris F.A. Johnson, 2017/08/31