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}"
done

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

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

Read file into array – you don’t need to loop trough each line

Use bash internal command readarray. -t option removes trailing newline. More options look in man bash. Following will read each line of file.txt into indexed array named indexed_array.

readarray -t indexed_array < file.txt

Add command output into an array – same thing, you don’t need loop

Use bash internal command readarray. -t option removes trailing newline. More options look in man bash. Following will read each line of ps -ef into indexed array named indexed_array. Note the double < < separated with space. This is called process substitution. This feeds command output into stdin of the readarray command. NB! dont leave space between last < and the brackets.

readarray -t indexed_array < <(ps -ef)

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