FreeKB - Bash Shell Scripting Getting Started with Arrays
Bash Shell Scripting - Getting Started with Arrays

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

fruit=()

 

In this example, an array named fruit is created, and the array contains different types of fruit.

fruit=(apple banana orange grapes)

 

The echo command will only print the first item in the array.

echo $fruit

 

In this example, the echo command would only print the first element in the array, "apple".

apple

 

Here is how to print every element in the array.

echo ${fruit[*]}

 

Which should return the following.

apple banana orange grapes

 


for loop

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

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

 

Which should return the following.

apple
banana
orange
grape

 


Index

Arrays can also created using index numbers.

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

 

Individual array items can then be printed using the array index number.

echo ${fruit[0]}
echo ${fruit[1]}
echo ${fruit[2]}
echo ${fruit[3]}

 

Or like this.

echo ${fruit[0]} ${fruit[1]} ${fruit[2]} ${fruit[3]}

 

Or like this, to print every item in the array.

echo ${fruit[*]}

 

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

apple
banana
orange
grape

 


Whitespace in elements

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

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

 

Also double quote the for loop.

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

 

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

apple
banana
orange
grape
honeydew melon

 


Count the number of items in an array

This array contains four items.

fruits=(apple banana orange grapes)


The number of items in an array can be printed like this.

echo ${#fruit[*]}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |