Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I add an element to array?? 2

Status
Not open for further replies.

AlbertAguirre

Programmer
Nov 21, 2001
273
0
0
US
I just want to add to the end of an array. How is this done??? Seems so simple...

Heres my array:
arEquipment=(albert danielle daniel);

I would like to add element 'nathan' to the end.

How?

 
Figured it out:

# CREATE ARRAY
arEquipment=(albert danielle daniel);

# APPEND TO IT
arEquipment=(${arEquipment[*]} nathan);

Is there another way?
 
Hi

It would be preferable to not reassign the whole array :
Code:
arEquipment[${#arEquipment[*]}]='nathan'
For speed matters :
Code:
[blue]master #[/blue] time for ((i=0;i<10000;i++)); do arr1=("${arr1[*]}" "$i"); done
real    0m14.505s
user    0m13.748s
sys     0m0.690s

[blue]master #[/blue] time for ((i=0;i<10000;i++)); do arr2[${#arr2[@]}]="$i"; done
real    0m0.150s
user    0m0.143s
sys     0m0.005s
Anyway, in such situations use at ( @ ) instead of asterisk ( * ) and also use double quotes ( " ). Otherwise multi-word values will be misinterpreted :
Code:
[blue]master #[/blue] a=( 'a b c' 'd e' ); a=( ${a[*]} 'f' ) [gray]# asterisk, no quotes[/gray]
[blue]master #[/blue] for ((i=0;i<${#a[*]};i++)); do echo "$i  ${a[i]}"; done
0  a
1  b
2  c
3  d
4  e
5  f
[blue]master #[/blue] a=( 'a b c' 'd e' ); a=( ${a[@]} 'f' ) [gray]# at, no quotes[/gray]
[blue]master #[/blue] for ((i=0;i<${#a[*]};i++)); do echo "$i  ${a[i]}"; done
0  a
1  b
2  c
3  d
4  e
5  f
[blue]master #[/blue] a=( 'a b c' 'd e' ); a=( "${a[*]}" 'f' ) [gray]# asterisk, quotes[/gray]
[blue]master #[/blue] for ((i=0;i<${#a[*]};i++)); do echo "$i  ${a[i]}"; done
0  a b c d e
1  f
[blue]master #[/blue] a=( 'a b c' 'd e' ); a=( "${a[@]}" 'f' ) [gray]# at, quotes[/gray]
[blue]master #[/blue] for ((i=0;i<${#a[*]};i++)); do echo "$i  ${a[i]}"; done
0  a b c
1  d e
2  f

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top