Is there a way to do something like PHPs $array[] = 'foo';
in bash vs doing:
array[0] = 'foo'
array[1] = 'bar'
Is there a way to do something like PHPs $array[] = 'foo';
in bash vs doing:
array[0] = 'foo'
array[1] = 'bar'
Yes there is:
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
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.
From the bash documentation:
Arrays are assigned to using compound assignments of the form
name=(value1 ... valueN)
where each VALUE is of the form
[[SUBSCRIPT]=]STRING
. If the optional subscript is supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. This syntax is also accepted by thedeclare
builtin. Individual array elements may be assigned to using thename['SUBSCRIPT']=VALUE
syntax introduced above.
If you array is always sequential and starts at 0, then you can do this:
array[${#array[@]}] = 'foo'
${#array_name[@]}
gets the length of the array
$ declare -a arr
$ arr=("a")
$ arr=(${arr[@]} "new")
$ echo ${arr[@]}
a new
$ arr=(${arr[@]} "newest")
$ echo ${arr[@]}
a new newest
As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]}
is not always the next item at the end of the array.
$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h
Here's how to get the last index:
$ end=(${!array[@]}) # put all the indices in an array
$ end=${end[@]: -1} # get the last one
$ echo $end
42
That illustrates how to get the last element of an array. You'll often see this:
$ echo ${array[${#array[@]} - 1]}
g
As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:
$ echo ${array[@]: -1}
i