Bash 5 reference · Shell Builtins and Syntax
arrays (Bash syntax)
Indexed and associative arrays: create, append, read elements, count, slice and loop over them safely.
Bash 5
Syntax
arr=(a b c) ${arr[i]} ${arr[@]} ${#arr[@]} ${!arr[@]} arr+=(d)
Parameters
| Parameter | Description |
|---|---|
"${arr[@]}" |
All elements, each as a separate word. |
${#arr[@]} |
Number of elements. |
${!arr[@]} |
Indexes or keys. |
${arr[@]:1:2} |
Slice: 2 elements from index 1. |
Examples
servers=(web-1 web-2 'db 1')
servers+=(cache)
echo "${#servers[@]} servers, last: ${servers[-1]}"
for s in "${servers[@]}"; do echo "- $s"; done
Output
4 servers, last: cache - web-1 - web-2 - db 1 - cache
Run this on your computer — see “Get Started” for setup.
declare -A owner=([api]=ana [web]=ben)
for k in $(printf '%s\n' "${!owner[@]}" | sort); do echo "$k: ${owner[$k]}"; done
Output
api: ana web: ben
Run this on your computer — see “Get Started” for setup.
Related
declare· Declare variables with attributes: arrays, associative arrays, integers, read-only values and exported variables.mapfile· Read all lines of input into an indexed array at once (also called readarray), optionally trimming newlines with -t.for· Loop over words, files, ranges or array elements, or use the C-style form for counters.- Bash Arrays and Associative Arrays · tutorial