> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Bash Associative Array

An associative array in Bash is a one-dimensional data structure that stores key-value pairs, where the indices (keys) are arbitrary strings rather than sequential integers. This feature requires Bash version 4.0 or higher. A critical Bash-specific limitation is that associative array keys **cannot be empty strings**; attempting to use an empty string as a key (e.g., `my_array[""]="value"`) will immediately result in a `bad array subscript` error.

## Declaration and Scoping

Unlike indexed arrays, associative arrays cannot be created implicitly by assignment. They must be explicitly declared before use using the `declare` built-in with the `-A` (uppercase A) option.

```bash theme={"dark"}
declare -A my_array
```

Because associative arrays must be explicitly declared, using `declare` inside a function implicitly makes the array local to that function's scope. To declare a global associative array from within a function, the `-g` flag (introduced in Bash 4.2) must be used:

```bash theme={"dark"}
declare -gA my_global_array
```

To declare an associative array as read-only, append the `-r` option. Read-only associative arrays must be initialized at the exact time of declaration using compound assignment, as subsequent assignments are prohibited:

```bash theme={"dark"}
declare -A -r my_readonly_array=(["first_key"]="value_1" ["second_key"]="value_2")
```

## Assignment

Values can be populated using individual element assignment or compound assignment syntax. Keys containing spaces or special characters must be quoted or escaped with backslashes to prevent word splitting.

**Individual Assignment:**

```bash theme={"dark"}
my_array["first_key"]="value_1"
my_array[second\ key]="value_2"
```

**Compound Assignment:**

```bash theme={"dark"}
declare -A my_array=(
    ["first_key"]="value_1"
    ["second key"]="value_2"
)
```

## Accessing Elements

Values are retrieved using standard parameter expansion syntax, specifying the string key within the brackets.

```bash theme={"dark"}
echo "${my_array["first_key"]}"
```

## Checking Key Existence

To verify if a specific key exists in an associative array, use the `-v` test operator (introduced in Bash 4.2). This is the standard operation for key-value data structures. Checking for existence by evaluating the value (e.g., `if [ -n "${my_array[key]}" ]`) creates a bug if the key exists but holds an empty string.

```bash theme={"dark"}
if [[ -v my_array["first_key"] ]]; then
    echo "Key exists."
fi
```

## Retrieving Keys and Values

Bash provides specific parameter expansion operators to extract all keys or all values from the array. The `@` operator expands to all elements, treating each as a separate word when double-quoted.

**Retrieve all values:**

```bash theme={"dark"}
echo "${my_array[@]}"
```

**Retrieve all keys:**
Prefixing the array name with `!` extracts the indices (keys) instead of the values.

```bash theme={"dark"}
echo "${!my_array[@]}"
```

## Iteration

Iteration is typically performed by looping over the expanded list of keys, which allows access to both the key and its corresponding value within the loop body.

```bash theme={"dark"}
for key in "${!my_array[@]}"; do
    echo "Key: $key | Value: ${my_array[$key]}"
done
```

*Note: Associative arrays are inherently unordered. The iteration order of keys is not guaranteed to match the insertion order.*

## Array Length

The total number of key-value pairs stored in the associative array is calculated by prefixing the array name with the `#` length operator and using `@` as the index.

```bash theme={"dark"}
echo "${#my_array[@]}"
```

## Deletion

The `unset` built-in is used to remove individual key-value pairs or to destroy the entire array structure from memory.

When unsetting a specific element, the array reference must be quoted or escaped. If left unquoted, Bash treats the square brackets as a globbing character class, which can lead to unintended pathname expansion if a matching file exists in the current directory.

If the key is a literal string, single quotes or backslash escaping can be used. However, if the key is stored in a variable, double quotes **must** be used so the variable can expand while still protecting the brackets from pathname expansion.

**Remove a specific element safely:**

```bash theme={"dark"}
unset 'my_array[first_key]'
unset my_array\[second_key\]
unset "my_array[$key]"
```

**Remove the entire array:**

```bash theme={"dark"}
unset my_array
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Bash Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
