Arrays in Linux Bash

Home > Search
  by

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 "apple". A for loop can be used to iterate over each item in the array. 

apple

 


For each loop

In this example, a for loop is used to print each item in the array.

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

 

In this example, the for loop will print each piece of fruit.

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

 


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




Comments