Associative Arrays in Shell

Level 5210 keystrokes

An associative array (declare -A, Bash 4+) stores settings under string keys. A for loop over ${!config[@]} prints each key and value, then all keys and all values are printed. Bash does not keep insertion order, so the order may differ.

Shell code

# declare -A makes config an associative array (Bash 4+)
1declare -A config
# Store values under string keys
2config["host"]="localhost"
3config["port"]="8080"
4config["user"]="admin"
# Loop over the keys; the order is not guaranteed
5for key in "${!config[@]}"; do
# Look up the value for the current key
6 echo "$key = ${config[$key]}"
7done
# ${!config[@]} expands to all keys
8echo "Keys: ${!config[@]}"
# ${config[@]} expands to all values, in the same order as the keys
9echo "Values: ${config[@]}"

Output

host = localhost
port = 8080
user = admin
Keys: host port user
Values: localhost 8080 admin
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 20
  • [× 7
  • ]× 7
  • $× 6
  • {× 4
  • }× 4
  • =× 4
  • @× 3
  • :× 2
  • !× 2

More Shell examples at level 5

← Shell typing practice