Skip to content

Arrays

Integer-indexed Arrays

Displaying Arrays

printf "%s\n" "${BASH_VERSINFO[0]}"
printf "%s\n" "${BASH_VERSINFO[1]}"

Expands to single word with the value of each array element separated by the first character of the IFS special variable: 

printf "%s\n" "${BASH_VERSINFO[*]}"

Expands to each element in array to a separate word: 

printf "%s\n" "${BASH_VERSINFO[@]}"

Get second and third elements from array (as single word or as separate words): 

printf "%s\n" "${BASH_VERSINFO[*]:1:2}" printf "%s\n" "${BASH_VERSINFO[@]:1:2}"

Length of Array

Display the number of elements in the array: 

printf "%s\n" "${#BASH_VERSINFO[*]}"

Display the length of element #4 (counting from 0) in the array: 

printf "%s\n" "${#BASH_VERSINFO[4]}"

Assigning Array Elements

myarray=(China Singapore Malaysia "Sri Lanka") 
printf "%s\n" "${myarray[@]}" 

Using the += operator: 

myarray=() 
myarray+=(A) 
myarray+=(B C "and something else") 

printf "%s\n" "${myarray[@]}" 

Associative Arrays

declare -A myarray 

for subscript in a b c 
do 
  myarray[$subscript]="$subscript $RANDOM" 
done 

printf "%s\n" "${myarray["c"]}" 
printf "%s\n" "${myarray[@]}"