Bash Arrays

Bash arrays store ordered lists of values in a single variable, accessed by numeric index.

#Jobseeker

Find matching jobs & Auto apply with AI

Hyring
Jobseeker using Hyring to search, apply, and prepare with AI

Declaring and Populating Arrays

You can create an array implicitly by assigning values in parentheses, or explicitly with declare -a name. Indexing starts at zero, and array elements can be strings or numbers, mixed freely since Bash has no strict typing.

Example

#!/bin/bash
declare -a fruits
fruits=("apple" "banana" "cherry")

echo "${fruits[0]}"
echo "${fruits[1]}"

Accessing All Elements and the Length

${arr[@]} expands to every element as separate words, which is ideal for looping. ${#arr[@]} gives the number of elements in the array, and ${!arr[@]} gives the list of valid indices, which is handy when an array has gaps.

Example

#!/bin/bash
fruits=("apple" "banana" "cherry")

echo "Total fruits: ${#fruits[@]}"

for fruit in "${fruits[@]}"; do
  echo "Fruit: $fruit"
done

Adding, Updating, and Removing Elements

Append an element with arr+=("value"), overwrite an existing one by assigning directly to its index, and delete one with unset 'arr[index]'. Note that unset leaves a gap in the indices rather than shifting later elements down.

  • arr[0]="value" -- set or overwrite the element at index 0
  • arr+=("value") -- append a new element to the end
  • unset 'arr[1]' -- remove the element at index 1 (leaves a gap)
  • ${arr[@]:1:2} -- slice: 2 elements starting at index 1

Example

#!/bin/bash
colors=("red" "green" "blue")
colors+=("yellow")
colors[1]="lime"
unset 'colors[0]'

for i in "${!colors[@]}"; do
  echo "Index $i: ${colors[$i]}"
done
Note: Always quote array expansions as "${arr[@]}" -- without quotes, elements containing spaces get split into extra words.
Note: ${arr[@]} and ${arr[*]} look similar but behave differently when quoted: "${arr[@]}" keeps each element separate, while "${arr[*]}" joins them into one string.

Exercise: Bash Arrays

How do you declare an array containing three elements in Bash?