Bootstrap FreeKB - Bash (Scripting) - Append values to a list (+=)
Bash (Scripting) - Append values to a list (+=)

Updated:   |  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 Buy Me A Coffee



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

Add a Comment


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