help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Wrong result for assign subarray to itself?


From: Qu Wenruo
Subject: Re: [Help-bash] Wrong result for assign subarray to itself?
Date: Tue, 11 Nov 2014 09:02:07 +0800
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.2.0

-------- Original Message --------
Subject: Re: [Help-bash] Wrong result for assign subarray to itself?
From: Greg Wooledge <address@hidden>
To: Qu Wenruo <address@hidden>
Date: 2014年11月10日 21:36
On Mon, Nov 10, 2014 at 05:31:44PM +0800, Qu Wenruo wrote:
$ words=('word1' 'word2' 'word3')
$ echo address@hidden
word1 word2 word3            # OK
Your array assignment above is correct.  In general, you will want to use
the form "address@hidden" with quotes when expanding the array.
Thanks for the tip.

$ address@hidden:1}
This assignment probably doesn't do what you want.  You are not assigning
to a new array here, but rather to a scalar/string variable.  So, bash
expands the array to a list of words, then joins them together into a
string.

$ echo address@hidden
word2 word3 word2 word3  # What happens here??!!
# Shouldn't the result be ('word2' 'word3') ??
You get more information if you use declare -p instead of echo:

imadev:~$ words=('word1' 'word2' 'word3')
imadev:~$ address@hidden:1}
imadev:~$ declare -p words
declare -a words='([0]="word2 word3" [1]="word2" [2]="word3")'

Your scalar assignment overwrote the contents of words[0] with the
concatenated sub-list.  But words[1] and words[2] remained untouched.
Thanks for the explain, I'd better learn to use declare instead of echo for debugging.

Now, if what you are *really* trying to do is to create a new array
which is a sub-list of the prior array, then this is how you should
have done it:

words=("address@hidden:1}")
That's what I want, thanks a lot!

Thanks,
Qu

Or, if what you are *really* trying to do is remove the 0th element
from an existing array, do this:

unset 'words[0]'

The former creates a new array, with indices 0, 1, 2, etc.  The latter
simply removes one element from the existing array, so the remaining
indices will be 1, 2, 3, etc.  An array of this kind is called a "sparse
array", and the indices may not be a contiguous sequence of integers.

imadev:~$ words=(these are some "nice and neat" words)
imadev:~$ unset 'words[1]'
imadev:~$ declare -p words
declare -a words='([0]="these" [2]="some" [3]="nice and neat" [4]="words")'




reply via email to

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