[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Zero-length indexed arrays
From: |
Lawrence Velázquez |
Subject: |
Re: Zero-length indexed arrays |
Date: |
Thu, 16 Dec 2021 23:45:04 -0500 |
User-agent: |
Cyrus-JMAP/3.5.0-alpha0-4524-g5e5d2efdba-fm-20211214.001-g5e5d2efd |
On Thu, Dec 16, 2021, at 11:01 PM, Dale R. Worley wrote:
> A bit ago I was debugging a failing script at work. It turns out that
> when you say
> FOO=(x y z)
> then the variable FOO is an array and is defined. But when you say
> FOO=()
> then the variable FOO is an array (because ${#FOO[*]} substitutes an
> integer viz. 0) but it is *not* defined (because ${FOO[*]} generates an
> error when "set -u" is in effect).
Did you mean to say that ${#FOO[*]} causes an error? Because
${FOO[*]} does not, à la $*:
% bash --version | head -n 1
GNU bash, version 5.1.12(1)-release (x86_64-apple-darwin18.7.0)
% bash -uc ': "${FOO[*]}"'
% bash -uc ': "${#FOO[*]}"'
bash: line 1: FOO: unbound variable
> It turns out that this can matter, if you do something like this:
>
> set -u # for safety
> ...
> if ...
> then
> FOO=(...)
> else
> FOO=()
> fi
> ...
> FOO_PLUS=("${FOO[@]}" x y z w)
I have to assume you meant something else here as well. This example
never causes any errors.
% cat foo.bash; echo
set -u
if [[ -n "${1+set}" ]]; then
FOO=(a b c)
else
FOO=()
fi
FOO_PLUS=("${FOO[@]}" x y z w)
declare -p FOO_PLUS
% bash foo.bash
declare -a FOO_PLUS=([0]="x" [1]="y" [2]="z" [3]="w")
% bash foo.bash woot
declare -a FOO_PLUS=([0]="a" [1]="b" [2]="c" [3]="x" [4]="y" [5]="z"
[6]="w")
Like ${FOO[*]}, ${FOO[@]} and $@ are exempt from ''set -u''.
--
vq
- Zero-length indexed arrays, Dale R. Worley, 2021/12/16
- Re: Zero-length indexed arrays,
Lawrence Velázquez <=
- Re: Zero-length indexed arrays, Lawrence Velázquez, 2021/12/16
- Re: Zero-length indexed arrays, Dale R. Worley, 2021/12/21
- Re: Zero-length indexed arrays, Greg Wooledge, 2021/12/21
- Re: Zero-length indexed arrays, konsolebox, 2021/12/22
- Re: Zero-length indexed arrays, L A Walsh, 2021/12/22
- Re: Zero-length indexed arrays, Lawrence Velázquez, 2021/12/22
- Re: Zero-length indexed arrays, Chet Ramey, 2021/12/22