Indexed and associative arrays in bash
Linux #linux #bashIndexed arrays
In bash, indexed arrays can be created in two ways
- Declaring explicitly:
declare -a my_arr - Creating with initial values:
other_arr=(a b c)
declare -a my_arr # declare a new array
other_arry=() # create new array
Associative arrays or maps
Associative arrays are key value pairs and can be declared using declare keyword with -A switch
declare -A associative_arr
Adding elements to arrays
- Indexed arrays
declare -a my_arr
my_arr+=(a)
my_arr+=(b)
- Associative arrays
declare -A map
map=([foo]="bar" ["baz"]="other")
map["key"]="value"
Size of the array
#my_arr[@] - returns the size of array (see for loop example below)
Getting elements from arrays
There are two ways to get elements from arrays
my_arr[@]- returns all elements of arrays asseparatewordsmy_arr[*]- returns all elements of arrays as asinglestring
- Iterating over
associativearray
#!/bin/bash
declare -A map
map=([foo]="bar" ["baz"]="other")
map["key"]="value"
for value in "${map[@]}"; do
echo "$value"
done
Output
bar
other
value
- Iterating over
indexedarray
#/bin/bash
declare -a arr # indexed array
arr+=(a)
arr+=(b c)
for value in "${arr[@]}"; do
echo "${value}"
done
Output
a
b
c
Another way to iterate over indexed array is using for loop
#!/bin/bash
declare -a arr
arr+=(a)
arr+=(b c)
size=${#arr[@]}
for ((i=0;i<$size;i++)); do
echo "index $i, value: ${arr[$i]}"
done
Output
index 0, value: a
index 1, value: b
index 2, value: c
Iterating over keys of arrays
!arr[@] returns the keys of arrays, in case of indexed arrays these are indices while for associative arrays this will return actual keys.
- Example
#!/bin/bash
# indexed array
declare -a arr
arr+=(a)
arr+=(b c)
for k in "${!arr[@]}"; do
echo "keys $k"
done
# associative array
echo -e "\n"
declare -A map
map=([foo]="bar" ["baz"]="other")
map["key"]="value"
for value in "${map[@]}"; do
echo "$value"
done
Output
keys 0
keys 1
keys 2
bar
other
value
Deleting element from array
- Associative array:
unset map[key] - Indexed array:
unset arr[index]
#!/bin/bash
declare -a arr
arr+=(a)
arr+=(b c)
unset arr[0] # delete element at index 0
for k in "${!arr[@]}"; do
echo "keys $k"
done
Output
keys 1
keys 2
Note that after deletion indices will remain
samefor other elements i.e. there isnoelement at position0now, only index1&2has values