Shell Variables   «Prev  Next»
Lesson 10Using array variables
ObjectiveExplain and apply indexed and associative arrays in Bash shell scripts.

Using Array Variables in Shell Scripting (Modern Bash)

In shell scripts you’ll often group related values—flight numbers, filenames, or user IDs—and process them together. In POSIX sh there are no arrays; in Bash (and Korn shells) you have true arrays, which makes iteration, filtering, and passing related data much easier.

Indexed arrays (0-based)

Declare and initialize:


# Compact initialization
flights=(1424 1425 492 1720)

# Explicit indices (0-based by default)
flights[0]=1424
flights[1]=1425
flights[2]=492
flights[3]=1720

Access elements and length:

echo "First flight: ${flights[0]}"
echo "Count: ${#flights[@]}"     # number of elements

Append and insert:

flights+=("1880")     # append to the end
flights[10]=9001      # creates a sparse array (indices 4..9 empty)

Delete elements:

unset 'flights[1]'    # remove element at index 1
echo "${flights[@]}"  # index 1 is now empty

Array slicing:

# Get 2 elements starting from index 1
subset=("${flights[@]:1:2}")
echo "${subset[@]}"

Iterate (indices and values):

# Values (preserves spaces/newlines in elements)
for f in "${flights[@]}"; do
  echo "Flight: $f"
done

# Indices + values
for i in "${!flights[@]}"; do
  echo "flights[$i] = ${flights[$i]}"
done

All elements vs single string:

# "${arr[@]}"  → expands to N separate words (safe for spaces)
# "${arr[*]}"  → expands to one word (joined by IFS)
printf '%s\n' "${flights[@]}"   # preferred for robust loops

Associative arrays (key → value)

Great for lookups (Bash 4+):

declare -A airport_city=(
  [SFO]="San Francisco"
  [JFK]="New York"
  [DFW]="Dallas–Fort Worth"
)

echo "${airport_city[JFK]}"     # → New York

for k in "${!airport_city[@]}"; do
  echo "$k → ${airport_city[$k]}"
done

Reading data into arrays

# From a newline-separated file
mapfile -t flights < flights.txt   # each line becomes one element (no trailing newlines)

# From a command safely (no word-splitting surprises)
mapfile -t users < <(getent passwd | cut -d: -f1)

Passing arrays to functions

Use name references (Bash 4.3+):

print_list() {
  local -n ref="$1"   # name reference to an array variable
  for x in "${ref[@]}"; do printf '%s\n' "$x"; done
}

print_list flights

Common pitfalls & best practices

Conceptual difference between scalar and array variables:
Array (indexed)
flights[0] = 1424
flights[1] = 1425
flights[2] = 492
flights[3] = 1720

Scalars (separate variables)
FLIGHT1 = 1424
FLIGHT2 = 1425
FLIGHT3 = 492
FLIGHT4 = 1720

Print all elements quickly

echo "${flights[@]}"     # prints each element as a separate word
printf '%s\n' "${flights[@]}"   # one per line (safer for logs)

Summary

Arrays make Bash scripts clearer and safer whenever you manage lists or key–value pairs. Prefer arrays over ad-hoc variable naming, iterate with "${!arr[@]}", and always quote expansions. For strict POSIX sh, plan alternatives or use Bash.


SEMrush Software 5 SEMrush Banner 5