Arrays and associative arrays
Indexed arrays, "${arr[@]}", sorting through sort, and key/value maps with declare -A.
Runs in Zerethon IDE · Bash 5.2
Official Bash documentation ↗
main.sh
scores=(70 95 82)
scores+=(60)
echo "${scores[0]} ${scores[-1]} ${#scores[@]}"
echo "all: ${scores[*]}"
mapfile -t sorted < <(printf '%s\n' "${scores[@]}" | sort -n)
echo "sorted: ${sorted[*]}"
echo "slice: ${sorted[*]:1:2}"
for s in "${scores[@]}"; do
if (( s > 80 )); then echo "high: $s"; fi
done
declare -A ages=([ada]=36 [alan]=41)
ages[grace]=85
echo "${ages[linus]:-unknown} ${#ages[@]}"
for name in $(printf '%s\n' "${!ages[@]}" | sort); do
echo "$name ${ages[$name]}"
done
[[ -v ages[alan] ]] && echo "alan is there"
Output
70 60 4 all: 70 95 82 60 sorted: 60 70 82 95 slice: 70 82 high: 95 high: 82 unknown 3 ada 36 alan 41 grace 85 alan is there
- Loop over
"${arr[@]}"(with the quotes) so elements with spaces stay whole. ${#arr[@]}is the number of elements;${!arr[@]}the indexes or keys.- An associative array must be declared with
declare -Afirst. Its keys come out in no particular order. mapfile -t arr < <(command)reads a command's output into an array, one line per element.