bhylu.com

Advertisements

Bash Associative Arrays

Use named keys while making output order deliberate.

How it works

Associative arrays map keys to values and require Bash 4 or newer. They are useful for small in-memory lookups such as expected batch sizes. Their iteration order is not a reporting contract, so choose or sort the output keys explicitly when reproducibility matters. Validate arbitrary keys according to the application rather than treating the array as a full database.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

associative-arrays.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
declare -A sheets=([north]=8 [south]=5)
for area in north south; do
    printf "%s=%d\n" "$area" "${sheets[$area]}"
done

Expected result

north=8
south=5

The output order comes from the explicit area list, not from the associative array’s internal order. The keys are fixed trusted labels in this listing. For data from a file, validate the key vocabulary and missing-key behaviour, especially with nounset enabled. Arrays are shell-local state and vanish when the process exits.

Primary technical reference: Bash documentation.