Bash (Scripting) - Append values to an array (+=)

If you are not familiar with arrays, check out our article Getting Started with Arrays in Bash Shell Scripting.

Let's say you have an array of fruit.

fruit=(banana apple orange grapes)


The += operator can be used to append values to the array. In this example, pineapple is appended to the fruit array.



Here is how to print every element in the array.

echo ${food[*]}


Which should return the following.

apple banana orange grapes pineapple


Or, a for loop can be used to iterate over each item in the array, like this.

for item in ${fruit[@]}; do
  echo $item


Which should return the following.



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 83fa2 in the box below so that we can be sure you are a human.


July 24th, 2020 by Robin A. Meade
echo "$fruit" # prints the first element of the array printf '%s\n' "${fruit[@]}" # prints each element on its own line IFS=',' echo "${fruit[*]}" # prints comma separated values IFS=$' \t\n' # Restores IFS to its default value

Web design by yours truely - me, myself, and I   |   |