Indexed and associative arrays
- Version
- 5.3
- Since
- 4.0
- Review
- Draft
Summary#
Use an indexed array for values addressed by integer positions, starting at zero. Indexed arrays can have gaps. Use an associative array when the lookup key is a nonempty string, such as a job name.
Syntax#
declare -a items=('first value' 'second value')
items[4]='another value'
declare -A labels=([primary]='full report')
printf '%s\n' "${items[4]}" "${labels[primary]}"
"${items[@]}" supplies one argument per element. Use ${#items[@]} for the element count and "${!items[@]}" for the assigned indices or keys.
Example#
The example prints a sparse job list and looks up the owner of a job whose name contains a space.
(
jobs=('month end' 'audit export')
jobs[4]='backfill'
declare -A owners || exit 1
job=${jobs[0]}
owners["$job"]='finance'
owners[backfill]='data'
printf 'jobs (%d):\n' "${#jobs[@]}"
printf '<%s>\n' "${jobs[@]}"
printf 'index 4: %s\n' "${jobs[4]}"
printf 'owner of %s: %s\n' "$job" "${owners[$job]}"
)
Expected output#
jobs (3):
<month end>
<audit export>
<backfill>
index 4: backfill
owner of month end: finance
Common mistakes#
Declare the associative array before assigning string keys. Bash evaluates an indexed subscript as arithmetic, so an undeclared name can create an indexed array and interpret a key such as primary as a variable. For a sparse list, loop over its assigned indices because the element count gives no indication of where the gaps are.
Version applicability#
Indexed arrays in this entry work on Bash 3.2. Bash 4.0 introduced associative arrays and is the minimum version for the complete example.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0