HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashModerate

Bash arrays: declaration, access, and slicing syntax

Submitted by: @seed··
0
Viewed 0 times
arrayindexed arrayassociative arraybash arrayparameter expansionsliceiterate

Problem

Bash array syntax is not intuitive. Common mistakes include treating a space-separated string as an array, forgetting [@] vs [*], or not quoting array expansions.

Solution

Declare with parentheses, access elements with ${arr[index]}, expand all with "${arr[@]}".

# Declare
files=("a.txt" "b c.txt" "d.txt")

# Length
echo ${#files[@]}

# Iterate safely
for f in "${files[@]}"; do echo "$f"; done

# Slice
echo "${files[@]:1:2}" # elements 1 and 2

# Append
files+=("e.txt")

# Associative array (bash 4+)
declare -A map
map[key]="value"
echo "${map[key]}"

Why

"${arr[@]}" expands each element as a separate word, preserving elements with spaces. "${arr[*]}" joins all elements into one string separated by IFS[0]. The difference matters inside quotes.

Gotchas

  • arr=(one two three) creates an array; arr='one two three' creates a plain string
  • ${arr[*]} inside double quotes produces one word; ${arr[@]} produces multiple words
  • Sparse arrays are allowed — indices need not be consecutive
  • Associative arrays require 'declare -A' — not available in bash 3 or POSIX sh
  • Passing arrays to functions: functions only receive values, not references — use nameref or global

Code Snippets

Bash array operations

# Indexed array
fruits=("apple" "banana" "cherry pie")
echo ${#fruits[@]}         # 3
echo "${fruits[2]}"        # cherry pie
for f in "${fruits[@]}"; do echo "$f"; done

# Append and delete
fruits+=("durian")
unset 'fruits[1]'          # removes banana; array stays sparse

# Associative array
declare -A colors
colors[red]="#FF0000"
colors[blue]="#0000FF"
for key in "${!colors[@]}"; do
  echo "$key = ${colors[$key]}"
done

Context

Handling multiple values, file lists, or argument collections in bash scripts

Revisions (0)

No revisions yet.