Accessing array values

Once we have initialized an array, we can access it, as follows:

${array_name[index]}

Create script array_01.sh, as follows:

#!/bin/bash 
 
FRUIT[0]="Pear" 
FRUIT[1]="Apple" 
FRUIT[2]="Mango" 
FRUIT[3]="Banana" 
FRUIT[4]="Papaya" 
echo "First Index: ${FRUIT[0]}" 
echo "Second Index: ${FRUIT[1]}" 

The output is as follows:

$ chmod +x array_01.sh$./array_01.shFirst Index: PearSecond Index: Apple

To display all the items from the array, use the following commands:

${FRUIT[*]}${FRUIT[@]}

Create script array_02.sh, as follows:

#!/bin/bash 
FRUIT[0]="Pear" 
FRUIT[1]="Apple" 
FRUIT[2]="Mango" 
FRUIT[3]="Banana" 
FRUIT[4]="Papaya" 
echo "Method One : ${FRUIT[*]}" 
echo "Method Two : ${FRUIT[@]}" 

The output is as follows:

$ chmod +x array_02.sh ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.