Bash Accessing Array Elements


Example

Print element at index 0

echo "${array[0]}"
4.3

Print last element using substring expansion syntax

echo "${arr[@]: -1 }"
4.3

Print last element using subscript syntax

echo "${array[-1]}"

Print all elements, each quoted separately

echo "${array[@]}"

Print all elements as a single quoted string

echo "${array[*]}"

Print all elements from index 1, each quoted separately

echo "${array[@]:1}"

Print 3 elements from index 1, each quoted separately

echo "${array[@]:1:3}"

String Operations

If referring to a single element, string operations are permitted:

array=(zero one two)
echo "${array[0]:0:3}" # gives out zer (chars at position 0, 1 and 2 in the string zero)
echo "${array[0]:1:3}" # gives out ero (chars at position 1, 2 and 3 in the string zero)

so ${array[$i]:N:M} gives out a string from the Nth position (starting from 0) in the string ${array[$i]} with M following chars.