Bash Tutorial · Bash Scripting · Lesson 20 of 30

Bash Arrays and Associative Arrays

Store lists in indexed arrays and key-value pairs in associative arrays.

Create a free account to save this page, take notes and track your progress. Sign in

Indexed arrays

Indexed arrays
servers=("web-1" "web-2" "db 1")
servers+=("cache-1")
echo "count: ${#servers[@]}"
echo "first: ${servers[0]}"
for s in "${servers[@]}"; do echo "- $s"; done
echo "slice: ${servers[*]:1:2}"

Output

count: 4
first: web-1
- web-1
- web-2
- db 1
- cache-1
slice: web-2 db 1

Run this on your computer — see “Get Started” for setup.

Always loop with "${arr[@]}" (quoted) so elements with spaces stay intact.

Associative arrays

declare -A creates a map from strings to strings (Bash 4+):

Associative arrays
declare -A ports=([web]=80 [api]=8080)
ports[db]=5432
for svc in $(printf '%s\n' "${!ports[@]}" | sort); do
  echo "$svc -> ${ports[$svc]}"
done
[[ -v ports[api] ]] && echo "api is configured"

Output

api -> 8080
db -> 5432
web -> 80
api is configured

Run this on your computer — see “Get Started” for setup.

Test yourself

How do you get the number of elements in array arr?

  1. ${arr.length}
  2. ${#arr[@]}
  3. len(arr)
  4. $arr[count]
Show answer

Answer: ${#arr[@]}

Was this page helpful?