[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Indirect expansion and arrays
From: |
Chet Ramey |
Subject: |
Re: Indirect expansion and arrays |
Date: |
Tue, 02 Oct 2012 09:26:29 -0400 |
User-agent: |
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:15.0) Gecko/20120907 Thunderbird/15.0.1 |
On 10/2/12 7:38 AM, Techlive Zheng wrote:
>
>
>> On 7/29/10 4:55 PM, Bernd Eggink wrote:
>>> It seems that indirect expansion doesn't work with arrays:
>>>
>>> $ a=(x y z)
>>> $ b=a
>>> $ echo "${!b[0]} ${!b[1]} ${!b[2]}"
>>> x
>>>
>>> Is that intended? The documentation isn't explicit about it.
>
>> It does, but it doesn't work in the way you are trying. The `!' binds to
>> an entire variable reference, in this case 'b[0]'. The idea behind that
>> was to permit the use of an array of variable names, for instance, that
>> could be easily referenced using indirect expansion.
>
>> The following code will display
>> "x variable y variable z variable"
>
>> a=(x y z)
>
>> x='x variable'
>> y='y variable'
>> z='z variable'
>
>> echo "${!a[0]} ${!a[1]} ${!a[2]}"
>
>> Chet
>> --
>> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>> ``Ars longa, vita brevis'' - Hippocrates
>> Chet Ramey, ITS, CWRU chet@case.edu
>> http://cnswww.cns.cwru.edu/~chet/
>
> I think that indirect reference for fash variable should be used literally.
>
> $ a=(x y z)
> $ b=a[@]
> $ echo "${!b}" # this would work
>
> Combine with Chet Ramey's reply, a strucure like below would work.
>
> $ c=(a[0] a[1] a[2])
> $ echo "${!c[0]} ${!c[1]} ${!c[2]}" #this would work too
They both do work, in the sense that they both display `x y z'.
The next version of bash will have ksh93-style nameref variables, so
indirect references to a nameref variable will work as they do in ksh.
That's slightly different than how they work now, but backwards
compatible, since bash-4.2 doesn't have namerefs.
Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU chet@case.edu http://cnswww.cns.cwru.edu/~chet/