Indexed arrays use non-negative integers (0, 1, 2, ...) as keys.
| Section | Action | Syntax | Example |
|---|---|---|---|
| Declaration | Declare & Init | names=("Alice" "Bob" "Charlie") |
Creates an array with keys 0, 1, 2. |
| Basics | Access Value | ${names[1]} |
Output: "Bob" |
| All Values | ${names[@]} |
Output: "Alice Bob Charlie" | |
| All Keys | ${!names[@]} |
Output: "0 1 2" | |
| Count Elements | ${#names[@]} |
Output: 3 | |
| Add/Set Element | names[3]="David" |
Adds "David" at key 3. | |
| Remove Element | unset names[1] |
Removes "Bob" and leaves a gap in the keys. | |
| Looping | Loop Over Values | for name in "${names[@]}"; do echo "$name"; done |
Outputs: Alice, Bob, Charlie (on new lines) |
| Loop Over Keys | for i in "${!names[@]}"; do echo "Key $i: ${names[i]}"; done |
Outputs: Key 0: Alice, Key 1: Bob, ... |
Associative arrays use strings as keys. They must be declared with declare -A.
| Section | Action | Syntax | Example |
|---|---|---|---|
| Declaration | Declare & Init | declare -A config=(["host"]="server1" ["port"]=8080) |
Creates an array mapping string keys to values. |
| Basics | Access Value | ${config["host"]} |
Output: "server1" |
| All Values | ${config[@]} |
Output: "server1 8080" | |
| All Keys | ${!config[@]} |
Output: "host port" | |
| Count Elements | ${#config[@]} |
Output: 2 | |
| Add/Set Element | config["user"]="admin" |
Sets the value for the "user" key. | |
| Remove Element | unset config["port"] |
Removes the "port" key and its value. | |
| Looping | Loop Over Values | for value in "${config[@]}"; do echo "$value"; done |
Outputs: server1, 8080 (on new lines) |
| Loop Over Keys | for key in "${!config[@]}"; do echo "Key $key: ${config[$key]}"; done |
Outputs: Key host: server1, Key port: 8080 |
# Example: Find the key whose value is "server1"
target_value="server1"
found_key=""
for key in "${!config[@]}"; do
if [[ "${config[$key]}" == "$target_value" ]]; then
found_key="$key"
break
fi
done
echo "Key for value '$target_value' is: $found_key"