help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Indirect variable assignment with declare


From: Chet Ramey
Subject: Re: [Help-bash] Indirect variable assignment with declare
Date: Sat, 19 Aug 2017 20:14:16 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Thunderbird/52.2.1

On 8/17/17 5:41 PM, noone wrote:
> I wonder if the behavior demonstrated below is legit or is it a bug?

It's legit.

`declare' and its siblings `local' and `typeset' (and its cousins `export'
and `readonly') are what Posix calls declaration builtins: arguments that
are determined to be assignment statements are expanded as if they were
assignment statements.  Primarily this means no word splitting.

You can read the Posix discussion and interpretation at

http://austingroupbugs.net/view.php?id=351

> arg='--src'
> a='abc               def'
> 
> declare src=$a
> echo "src=[$src]" # src=[abc               def]
> declare src="$a"
> echo "src=[$src]" # src=[abc               def]

The arguments are both assignment statements, and that can be determined at
parse time.  They do not undergo word splitting, so src is assigned the
unsplit value of $a.

> 
> declare ${arg#--}=$a # <------ indirect assignment, no quotes
> echo "src=[$src]" # src=[abc] <------ $a got expanded in declare above

This is not a valid assignment statement at parse time, so it is not marked
as such and normal expansion, including word splitting, occurs.  This means
that the command turns into

        declare src=abc def

`declare' recognizes the assignment statement and performs it, and also
creates a new variable named `def' that has no value.

> declare ${arg#--}="$a"
> echo "src=[$src]" # src=[abc               def]

The quotes around $a suppress 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/



reply via email to

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