Bash (Scripting) - Combining lists

by
Jeremy Canfield |
Updated: March 14 2023
| 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 two lists, one contain fruit and the other containing veggies.
fruit=(apple banana orange grapes)
veggies=(onion pepper tomato carrot)
Here is how you could combine the values in the fruit and veggies list into a new list named food.
food=(${fruit[@]} ${veggies[@]})
Here is how to print every element in the list.
echo ${food[*]}
Which should return the following.
apple banana orange grapes onion pepper tomato carrot
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
grapes
onion
pepper
tomato
carrot
Did you find this article helpful?
If so, consider buying me a coffee over at