Chapter 12: Arrays

Bash supports 2 kinds of arrays:

  • Indexed Arrays: Set or Read values by referring to their position (using an index). Indexing is 0-based.
  • Associative Arrays (Bash v4 & above): These are key:value pairs
  • We cannot create nested arrays in Bash.

Defining Arrays

1 # Defining arrays: 2 ways
2 snacks=("apple" "banana" "orange")
3 declare -a stationery=("paper" "stapler")

Retrieving Values

1 # Retrieve Values - this is parameter expansion
2 echo ${snacks[2]}

Setting Values

1 # Set values by index number
2 snacks[5]="grapes"

Appending to an array

1 # Add to end of array
2 snacks+=("mango")

Length of an array

${#array_variable[@]} will retrieve the length

Looping through an array

1 for item in "${array_var[@]}"
2 do
3     # code
4 done

Associative Arrays

1 # Create an associative array
2 declare -A office
3 
4 # Set values
5 office["buillding name"]="HQ West"
6 
7 # Accessing values
8 echo ${office["building name"]}