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 a list of fruit. += can be used to append values to a list. In this example, pineapple is appended to the "fruit" list.

declare will return the structure of the list and echo will be used to print each value in the list.

fruit=(banana apple orange grapes)
fruit+=(pineapple)
declare -p fruit
echo ${fruit[*]}

 

Running this script should return the following.

declare -a fruit=([0]="banana" [1]="apple" [2]="orange" [3]="grapes" [4]="pineapple")
banana apple orange grapes pineapple

 

By default, whitespace is used to delimit the elements in the list.

#!/bin/bash
fruit=(banana apple orange grapes)
fruit+=(pineapple pears)
declare -p fruit
echo ${fruit[*]}

 

In this example, "pineapple" and "pears" will be unique elements in the list.

declare -a fruit=([0]="banana" [1]="apple" [2]="orange" [3]="grapes" [4]="pineapple" [5]="pears")
banana apple orange grapes pineapple pears

 

single or double quotes can be used to append a value that contains whitespace to the list.

#!/bin/bash
fruit=(banana apple orange grapes)
fruit+=("pineapple pears")
declare -p fruit
echo ${fruit[*]}

 

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

By default, the Internal Field Separator, commonly known as IFS, uses whitespace as the delimiter, so I often have to update IFS to use new lines as the delimiter.

IFS=$'\n'
for item in ${fruit[@]}; do
  echo $item
done
unset IFS

 

Which should return the following.

apple
banana
orange
grape
pineapple pears

 




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 6fae93 in the box below so that we can be sure you are a human.