Mutable list or array structure in Bash? How can I easily append to it? Mutable list or array structure in Bash? How can I easily append to it? arrays arrays

Mutable list or array structure in Bash? How can I easily append to it?


$ 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[@]})


foo=(a b c)foo=("${foo[@]}" d)for i in "${foo[@]}"; do echo "$i" ; done


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