Associative Array in Shell

Level 3134 keystrokes

declare -A creates an associative array whose keys are strings (Bash 4+). The values are read by key, and ${!config[@]} lists the keys; their order is not guaranteed.

Shell code

# declare -A makes config an associative array (needs Bash 4+)
1declare -A config
# Store "localhost" under the key host
2config[host]="localhost"
# Store 8080 under the key port
3config[port]=8080
# Read values by key: prints Server: localhost:8080
4echo "Server: ${config[host]}:${config[port]}"
# ${!config[@]} lists all keys; the order may differ from insertion
5echo "Keys: ${!config[@]}"

Output

Server: localhost:8080
Keys: host port
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.

  • "× 6
  • [× 5
  • ]× 5
  • :× 3
  • {× 3
  • }× 3
  • $× 3
  • =× 2
  • -× 1
  • !× 1

More Shell examples at level 3

← Shell typing practice