Bash (Scripting) - Append values to a list (+=)
by
Jeremy Canfield |
Updated: February 25 2024
| Bash (Scripting) articles
If you are not familiar with lists, check out our article Getting Started with Lists in Bash Shell Scripting.
Let's say you have an list of fruit.
fruit=(banana apple orange grapes)
The += operator can be used to append values to the list. In this example, pineapple is appended to the fruit list.
fruit+=(pineapple)
Here is how to print every element in the list.
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 list, like this.
for item in ${fruit[@]}; do
echo $item
done
Which should return the following.
apple
banana
orange
grape
pineapple
Did you find this article helpful?
If so, consider buying me a coffee over at
Comments
July 24 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