Skip to content
Arrays
step 1/5

Reading — step 1 of 5

Learn

~1 min readRobust Scripting

Bash supports two array types:

Indexed arrays (numeric keys):

fruits=(apple banana cherry)
fruits[3]="date"               # append at index 3
fruits+=(elderberry fig)        # append multiple

echo "${fruits[0]}"             # apple
echo "${fruits[@]}"             # all elements (preserves spaces — CRITICAL)
echo "${fruits[*]}"             # all elements (joined by IFS — usually space)
echo "${#fruits[@]}"            # count
echo "${!fruits[@]}"            # all indices
unset fruits[2]                  # remove

The "${arr[@]}" form (with quotes) preserves elements with spaces. Never use ${arr[@]} unquoted.

Associative arrays (string keys, requires Bash 4+):

declare -A ages
ages[alice]=30
ages[bob]=25

echo "${ages[alice]}"          # 30
for key in "${!ages[@]}"; do
    echo "$key: ${ages[$key]}"
done

Slicing:

fruits=(a b c d e)
echo "${fruits[@]:1:3}"        # b c d (start:length)

Iterate while preserving order:

for f in "${fruits[@]}"; do
    echo "$f"
done

For counters and reduces, prefer (( ... )) arithmetic:

sum=0
for n in "${nums[@]}"; do (( sum += n )); done
echo "$sum"

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…