Skip to main content

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.

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.
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:
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:
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:
my_array["first_key"]="value_1"
my_array[second\ key]="value_2"
Compound Assignment:
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.
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.
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:
echo "${my_array[@]}"
Retrieve all keys: Prefixing the array name with ! extracts the indices (keys) instead of the values.
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.
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.
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:
unset 'my_array[first_key]'
unset my_array\[second_key\]
unset "my_array[$key]"
Remove the entire array:
unset my_array
Master Bash with Deep Grasping Methodology!Learn More