bash how to add to array


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

echo ${array[@]}

Output: first_item

If your array is sequential, you can use "#" to get index for new 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.