With a little side of applesauce...

Monday, January 29, 2007

BASH - adding a value to the end of an array

Here is an example of adding a value to an array:

$ X[1]=alice
$ echo ${#X[@]}
1
$ X[2]=john
$ echo ${#X[@]}
2
$ for i in ${X[@]}; do echo $i ; done
alice
john
$ X[$(( ${#X[@]}+1 ))]=tom
$ for i in ${X[@]}; do echo $i ; done
alice
john
tom

The trick is:

X[$(( ${#X[@]}+1 ))]=tom

Though it looks confusing, all we are doing is finding the number of elements in the array:

${#X[@]}

Add 1 to the array:

$(( ${#X[@]}+1 ))

Use that value as an index:

X[$(( ${#X[@]}+1 ))]

And initialize the element with a value:

X[$(( ${#X[@]}+1 ))]=tom

No comments: