Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

bash array assignment

15 views
Skip to first unread message

Nicholas Geovanis

unread,
Feb 9, 2016, 8:24:41 PM2/9/16
to
How does one assign one array to another in bash? Normal assignment seems not to produce an array, just a string. See this code fragment for example:

[ngeo@localhost src]$ cat arraytst1.sh
#!/usr/bin/bash
names2=()
names=("Bob" "Peter" "$USER" "Big Bad John")
names2="${names[@]}"
for name in "${names[@]}"; do echo "$name"; done
for name in "${names2[@]}"; do echo "$name"; done
[ngeo@localhost src]$ ./arraytst1.sh
Bob
Peter
ngeo
Big Bad John
Bob Peter ngeo Big Bad John

Janis Papanagnou

unread,
Feb 9, 2016, 8:37:24 PM2/9/16
to
On 10.02.2016 02:24, Nicholas Geovanis wrote:
> How does one assign one array to another in bash? Normal assignment seems
> not to produce an array, just a string. See this code fragment for
> example:
>
> [ngeo@localhost src]$ cat arraytst1.sh
> #!/usr/bin/bash
> names2=()
> names=("Bob" "Peter" "$USER" "Big Bad John")
> names2="${names[@]}"

names2=( "${names[@]}" )


Janis

Nicholas Geovanis

unread,
Feb 9, 2016, 8:44:30 PM2/9/16
to
On Tuesday, February 9, 2016 at 7:24:41 PM UTC-6, Nicholas Geovanis wrote:
> How does one assign one array to another in bash? Normal assignment seems not > to produce an array, just a string. See this code fragment for example:

Managed to answer my own question, See below. Apologies for wasted bandwidth.
[ngeo@localhost src]$ cat arraytst1.sh
#!/usr/bin/bash
#names2=()
names=("Bob" "Peter" "$USER" "Big Bad John")
names2=("${names[@]}")

Stephane Chazelas

unread,
Feb 10, 2016, 5:40:14 PM2/10/16
to
2016-02-10 02:37:20 +0100, Janis Papanagnou:
> On 10.02.2016 02:24, Nicholas Geovanis wrote:
> > How does one assign one array to another in bash? Normal assignment seems
> > not to produce an array, just a string. See this code fragment for
> > example:
> >
> > [ngeo@localhost src]$ cat arraytst1.sh
> > #!/usr/bin/bash
> > names2=()
> > names=("Bob" "Peter" "$USER" "Big Bad John")
> > names2="${names[@]}"
>
> names2=( "${names[@]}" )
[...]

Note that it only works for non-sparse arrays. In the general
case, that would mess up the indices.

$ bash -c 'a=([12]=a [23]=b [34]=c); b=("${a[@]}"); declare -p a b'
declare -a a='([12]="a" [23]="b" [34]="c")'
declare -a b='([0]="a" [1]="b" [2]="c")'

To copy an array in bash, I think you need a loop:

b=()
for i in "${!a[@]}"; do
b[i]=${a[i]}
done

That's the same situation as ksh.

Arrays of all other shells (rc, es, csh, tcsh, zsh) are normal
arrays, not sparse, so the situation is a lot simpler there.

--
Stephane
0 new messages