I'm trying to collect string values in a bash script. What's the simplest way that I can append string values to a list or array structure such that I can echo them out at the end?
+2
A:
foo=(a b c)
foo=("${foo[@]}" d)
for i in "${foo[@]}"; do echo "$i" ; done
Ignacio Vazquez-Abrams
2010-01-06 14:06:56
+1
A:
The rather obscure syntax for appending to the end of an array in bash is:
myarr[${#myarr[*]}]=”$newitem”
ennuikiller
2010-01-06 14:07:14
As Dennis Williamson's answer points out, this is incorrect in some cases; bash arrays are sparse, and the index ${#myarr[*]} may not be the last index.
Evan Krall
2010-01-07 20:35:34
A:
To add to what Ignacio has suggested in another answer:
foo=(a b c)
foo=("${foo[@]}" d) # push element 'd'
foo[${#foo[*]}]="e" # push element 'e'
for i in "${foo[@]}"; do echo "$i" ; done
codaddict
2010-01-06 14:09:58
+4
A:
$ arr=(1 2 3)
$ arr+=(4)
$ echo ${arr[@]}
1 2 3 4
Since Bash uses sparse arrays, you shouldn't use the element count ${#arr}
as an index. You can however, get an array of indices like this:
$ indices=(${!arr[@]})
Dennis Williamson
2010-01-06 14:11:52
A:
$ for i in "string1" "string2" "string3"
> do
> array+=($i)
> done
$ echo ${array[@]}
string1 string2 string3
ghostdog74
2010-01-06 14:13:56