[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Wrong result for assign subarray to itself?
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] Wrong result for assign subarray to itself? |
Date: |
Mon, 10 Nov 2014 08:36:22 -0500 |
User-agent: |
Mutt/1.4.2.3i |
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.
> $ 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.
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}")
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")'