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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

arr=(a b c)  ${arr[i]}  ${arr[@]}  ${#arr[@]}  ${!arr[@]}  arr+=(d)

Parameters

ParameterDescription
"${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

Indexed arrays
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.

Looping over map keys
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.

Was this page helpful?