bash: arrays

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

Associative arrays:

# Local:
declare -A my_array
# Global:
declare -gA my_array

declare -A my_array=( ['']='empty' [0]='zero' ['a']='letter' )

# Add item to the array
my_array+=('banana'='fruit')

# Iterate over array:
for i in "${my_array[@]}"
do
        echo $i
done

Array indirection

Use a temporary variable to allow for array addressing indirection.

# $1 = 'my_array
declare -gA $1 # Declare array
# $1+=('banana'='fruit') # Will not work!
var=$1
var+=('banana'='fruit') # Ok. Adds an element to the array.

Also, consider this:

#!/bin/bash
function array_add {                                                                 
        eval `echo "$1['$2']='$3'"`                                                                                                                                        
}


declare -A my_map
my_map['first']='a'
my_map['second']='b'

my_array='my_map'
array_add $my_array 'third' 'c'                                                                                                                                            

for key in ${!my_map[@]}; do
        echo -e "[$key]\t ${my_map[$key]}"
done

Iterate over an array

#!/bin/bash
for element in "${my_array[@]}"
do
  echo "${element}"
done

To access the keys instead of the elements, add an exclamation mark:

#!/bin/bash
for key in "${!my_array[@]}"
do
  echo "${my_array[$key]}"
done

See also:

Issues related to this page:

ProjectSummaryStatusPriorityCategoryLast updatedAssigned to
ProgrammingBash: iterate over bash array in the order the …activenormalsupport request6 years 44 weeks