Bootstrap FreeKB - Bash (Scripting) - Getting Started with Lists
Bash (Scripting) - Getting Started with Lists

Updated:   |  Bash (Scripting) articles

A list in created by using the () characters. In this example, an empty list named fruit is created (the list contains no values).

fruit=()

 

In this example, a list named fruit is created, and the list contains different types of fruit.

fruit=(apple banana orange grapes)

 

declare can be used to show the index number of each element in the list.

declare -p fruit

 

Which should return the following.

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

 

You can use declare to create the array, like this.

declare -a "fruit=(apple banana orange grapes)"

 

Or like this.

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

 

Lists can also created using index numbers.

fruit[0]="apple"
fruit[1]="banana"
fruit[3]="orange"
fruit[4]="grape"

 

echo and print

The echo command will only print the first item in the list. In this example, echo would only print the first element in the list, "apple".

echo $fruit

 

wildcard can be used to print every element in the list.

echo ${fruit[*]}

 

Which should return the following.

apple banana orange grapes

 

Index numbers can be used to print a specific item in the list. In this example, "orange" would be printed.

echo ${fruit[2]}

 

for loop

A for loop can be used to iterate over each item in the list.

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

 

Which should return the following.

apple
banana
orange
grape

 

Whitespace in elements

Let's say elements in the list contain whitespace. In this example, "honeydew melon" contains whitespace. Double quote the elements in the list.

fruit=("apple" "banana" "orange" "grapes" "honeydew melon")

 

Also double quote the for loop.

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

 

In this example, each piece of fruit will be printed.

apple
banana
orange
grape
honeydew melon

 

Count the number of items in a list

# can be used to return the count of elements in the list.

echo ${#fruit[*]}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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