[Top][All Lists]

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

Re: declare a="$b" if $a previously set as array

From: konsolebox
Subject: Re: declare a="$b" if $a previously set as array
Date: Tue, 9 Dec 2014 20:55:02 +0800

On Tue, Dec 9, 2014 at 6:59 PM, Stephane Chazelas
<address@hidden> wrote:
> BTW, it's worth noting (and maybe documenting) that word
> splitting and filename generation are performed in:
> declare -g $var=$something
> (or declare ''var=$something or declare f\oo=$bar...)
> So it must be indeed:
> declare -g "$var=$something"

It actually should be completely avoided.  eval is the right tool for
that job (besides a variable declared with -n in 4.3+).

>> Anyhow, this problem would only happen if a variable in a specific
>> scope (and only in that scope) has already been set previously as an
>> array and it doesn't always happen if you write your scripts well.
>> > It may be worth recommending people do a "unset var" before
>> > doing a "declare [-<option>] var"
>> I actually find it better to mention that on a simple assignment like
>> declare var=$something, var's type doesn't change if it has already been
>> declared previously as an array.
> Strictly speaking,
> "if it has already been declared" *or assigned* (as in a[0]=x or
> a=()) "previously as an array" *in the current scope*,
> otherwise, the variable is declared as a scalar (but see below
> for more complications), :

Actually I referred to "declared" as to "being declared by type".  If it
comes to assigning values, it is more of "defining".  As for bash, using
an array form of assignment (e.g. a[0]=x; a=(x)) is an implied form of
declaration + definition.  Taking a quick glance at some of Bash's codes
you would see that variables are dynamically converted from a non-array
to an array type when it encounters an assignment (or perhaps and an
expansion) that requires one.  So saying that "if it has already been
declared previously as an array" should suffice on any form of
declaration whether there's an assignment of value or none.

See http://en.wikipedia.org/wiki/Declaration_%28computer_programming%29.

Clearly declare is already doing things more than what its name say.
Not that I'm saying it should no longer assign values, but at the very
least it should not be re-evaluating values.

As for the other things, I was actually only concerned about the
dangerous behavior that's synonymous to "eval $b" so I didn't really
thought about discussing them.  And I'm only referring to Bash when I
made the suggestions.  Other shells certainly does not support local


reply via email to

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