Bash arrays

There are two types of arrays you can use – indexed and associative arrays.

Start by declaring the arrays

$ declare -a indexed_array
$ declare -A associative_array

Add values to arrays – note the possibility to add values to arrays with += operator.

$ indexed_array[0]="value1"
$ indexed_array[1]="value2"
$ indexed_array[2]="value3"
$ indexed_array+="value4"
$ indexed_array+="value5"

$ associative_array[one]="value1"
$ associative_array[two]="value2"
$ associative_array[three]="value3"

# or add multiple values like this

$ indexed_array=(value6 value7 value8)
$ indexed_array+=(value4 value5)
$ associative_array=([one]=value1 [two]=value2 [three]=value3)
$ associative_array+=([four]=value4 [five]=value5)

Print out array values

$ echo ${indexed_array[@]}

# or 

$ echo ${associative_array[*]}

Print out array indexes or keys – add ! before array name

for index in "${!indexed_array[@]}"; do 
 echo "${index}"

for key in "${!associative_array[@]}"; do
echo "$key"

Number of values in arrays – use # before array name

echo "indexed array contains ${#indexed_array[@]} values"
echo "associative_array array contains ${#associative_array[@]} values"

Deleting values from an array – use unset

unset indexed_array[2]
unset associative_array[three]

Deleting entire array – useful if you play around with lost of data

unset indexed_array
unset associative_array

If you found this useful, say thanks, click on some banners or donate, I can always use some beer money.