Add a new element to an array without specifying the index in Bash

Darryl Hein picture Darryl Hein · Dec 23, 2009 · Viewed 622.5k times · Source

Is there a way to do something like PHPs $array[] = 'foo'; in bash vs doing:

array[0]='foo'
array[1]='bar'

Answer

Etienne Dechamps picture Etienne Dechamps · Dec 23, 2009

Yes there is:

ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')

Bash Reference Manual:

In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.