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

arrays, bash, scripting

Solution

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

Problem

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?

Original source