bash how to add to array

Answer

If you want to add new item to the end of array without specifying an index use:

array=()
array+=("first")
echo ${array[@]}

Output: first_item

If your array is sequential, you can use "#" to get index for new item:

array[${#array[@]}]="second_item"
echo ${array[@]}

Output: first_item second_item

Note "${#array[@]}" gets the length of the array.

Another option is assign to the array all of its items and append the new one as in the following example:

array=(${array[@]} "third_item")
echo ${array[@]}

Output: first_item second_item third_item

It 's good practice to enclose array items with quotes, when they could contain white space characters.

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.