help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Awkward behavior of empty arrays


From: Andy Chu
Subject: Re: [Help-bash] Awkward behavior of empty arrays
Date: Wed, 6 Sep 2017 11:53:20 -0700

On Tue, Sep 5, 2017 at 4:02 AM, Cristian Zoicas <address@hidden>
wrote:

>
>    set -u
>    unset A
>    declare -a A=()
>    echo "address@hidden"
>
>    The last statement will give you the error "bash: address@hidden: unbound
> variable".
>


Cristian, coincidentally I noticed a solution to your problem in the commit
description here:

https://github.com/NixOS/nixpkgs/commit/81194eef45e2c03018687be60c2c695a1729df36

In short, you can do:

$ argv ${A+"address@hidden"}

This works with set -u, including with an empty array.  (At least with bash
4.3 on my machine.)

You can compare the bad-interpolate vs. good-interpolate functions here
(please test with your bash version):

https://github.com/oilshell/blog-code/blob/master/empty-arrays/demo.sh

It's very similar in form to:

${1+"$@"}

- The outer substitution is NOT quoted
- The inner subsitution IS quoted
- Use + to test for unset, not :+ to test for unset or empty.  What "unset"
and "empty" mean in terms of arrays is fairly confusing.

It's not obvious to me why this works.  But it's also not clear to me why
there is a problem with "address@hidden" and set -u in the first place, because 
an
empty array "should be" distinct from an unset variable.  Probably the only
explanation is "ksh did it that way."

Andy


reply via email to

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