Arrays
Arrays in Bash allow you to store multiple values in a single variable. They're incredibly useful for working with lists, processing multiple files, and handling related data together. Bash supports both indexed arrays (with numeric indices) and associative arrays (with string keys, like a dictionary). Once you master arrays, you'll write more powerful and flexible scripts!
Declaring Arrays
In Bash, arrays can be declared in several ways. The simplest is assigning multiple values in parentheses.
Click Run to execute your code
# Different ways to declare arrays
# Method 1: Direct assignment
fruits=("apple" "banana" "cherry")
# Method 2: Explicit declare (optional)
declare -a numbers=(1 2 3 4 5)
# Method 3: Individual assignment
colors[0]="red"
colors[1]="green"
colors[2]="blue"
# Method 4: Sparse array (skip indices)
items[0]="first"
items[5]="fifth" # indices 1-4 are empty
- Bash arrays are zero-indexed (first element is at index 0)
- Indices don't have to be sequential (sparse arrays are allowed)
- You can start with any index number
Accessing Array Elements
Access individual elements using the syntax ${array[index]}. Always use braces when accessing array elements!
fruits=("apple" "banana" "cherry")
# Access individual elements
echo ${fruits[0]} # apple (first element)
echo ${fruits[1]} # banana (second element)
echo ${fruits[2]} # cherry (third element)
# Access all elements
echo ${fruits[@]} # All elements separately
echo ${fruits[*]} # All elements as one string
Array Length
Get the number of elements in an array using ${#array[@]}. This is different from string length!
fruits=("apple" "banana" "cherry")
# Number of elements
echo ${#fruits[@]} # Output: 3
# Length of specific element
echo ${#fruits[0]} # Output: 5 (length of "apple")
echo ${#fruits[@]} # Output: 3 (number of elements)
# Note the difference:
# ${#var} = length of string
# ${#array[@]} = number of array elements
Iterating Through Arrays
Use for loops to iterate through array elements. Always use "${array[@]}" to preserve spaces in elements.
fruits=("apple" "banana" "cherry")
# Iterate through values
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
# Iterate with indices
for i in "${!fruits[@]}"; do
echo "Index $i: ${fruits[$i]}"
done
# Iterate through indices
for index in "${!fruits[@]}"; do
echo "fruits[$index]=${fruits[$index]}"
done
"${array[@]}" (with quotes) when iterating! This preserves spaces in array elements. Unquoted ${array[@]} or using ${array[*]} can break with elements containing spaces.
Modifying Arrays
You can modify existing elements, add new elements, and remove elements from arrays.
fruits=("apple" "banana" "cherry")
# Modify an element
fruits[1]="blueberry"
echo ${fruits[@]} # apple blueberry cherry
# Add elements (append)
fruits+=("date" "elderberry")
echo ${fruits[@]} # apple blueberry cherry date elderberry
# Add single element
fruits+="fig" # Note: this appends to last element!
echo ${fruits[@]}
# Remove elements (creates sparse array)
unset fruits[2]
echo ${fruits[@]} # apple blueberry date elderberry (index 2 is gone)
unset an array element, it creates a "sparse" array with gaps. The indices don't automatically renumber. To remove gaps, you'd need to create a new array: new_array=("${old_array[@]}")
Associative Arrays (Bash 4+)
Associative arrays (also called hashes or dictionaries) use string keys instead of numeric indices. They're perfect for key-value storage.
Click Run to execute your code
# Declare associative array (Bash 4+)
declare -A person
# Assign values using string keys
person[name]="Alice"
person[age]=25
person[city]="New York"
# Access values
echo ${person[name]} # Alice
echo ${person[age]} # 25
# Get all keys
echo ${!person[@]} # name age city
# Get all values
echo ${person[@]} # Alice 25 New York
- Must be declared with
declare -A array_name- Use string keys instead of numeric indices
- Available in Bash 4.0 and later
- Perfect for configuration data, mappings, and key-value storage
Common Mistakes
1. Using $array instead of ${array[@]} or ${array[index]}
# Wrong - only gets first element
fruits=("apple" "banana" "cherry")
echo $fruits # Only prints: apple
# Correct - use ${array[@]} for all elements
echo ${fruits[@]} # Prints: apple banana cherry
# Or ${array[index]} for specific element
echo ${fruits[1]} # Prints: banana
2. Not using quotes when iterating arrays
# Wrong - breaks with spaces
items=("file one.txt" "file two.txt")
for item in ${items[@]}; do
echo "$item" # Prints: file, one.txt, file, two.txt (4 iterations!)
done
# Correct - use quotes
for item in "${items[@]}"; do
echo "$item" # Prints: file one.txt, file two.txt (2 iterations)
done
3. Confusing ${#array[@]} with ${#array[0]}
fruits=("apple" "banana")
# Wrong - gets length of first element, not array size
length=${#fruits} # Gets length of "apple" (5), not array size!
# Correct - use [@] for array length
size=${#fruits[@]} # Gets number of elements (2)
first_length=${#fruits[0]} # Gets length of first element (5)
4. Not declaring associative arrays
# Wrong - creates indexed array, not associative
person[name]="Alice" # Creates indexed array with index "name" (weird behavior)
# Correct - declare first
declare -A person
person[name]="Alice" # Creates associative array
Exercise: Work with Arrays
Task: Create a script that demonstrates array operations!
Requirements:
- Create an array with at least 5 elements
- Display the array length
- Display the first and last elements
- Modify one element
- Add two new elements
- Iterate through all elements and display them
- (Optional) Create an associative array with 3 key-value pairs
Show Solution
#!/bin/bash
# Array operations exercise
# Create array
colors=("red" "green" "blue" "yellow" "purple")
# Display array length
echo "Array length: ${#colors[@]}"
echo ""
# Display first and last elements
echo "First element: ${colors[0]}"
last_index=$((${#colors[@]} - 1))
echo "Last element: ${colors[$last_index]}"
echo ""
# Modify an element
colors[2]="cyan"
echo "After modifying index 2: ${colors[@]}"
echo ""
# Add elements
colors+=("orange" "pink")
echo "After adding elements: ${colors[@]}"
echo ""
# Iterate through array
echo "All colors:"
for color in "${colors[@]}"; do
echo " - $color"
done
echo ""
# Associative array example
declare -A person
person[name]="Alice"
person[age]=25
person[city]="New York"
echo "Associative array:"
for key in "${!person[@]}"; do
echo " $key: ${person[$key]}"
done
Summary
- Declaration:
array=(item1 item2 item3)ordeclare -a array - Access Element:
${array[index]}(zero-indexed) - All Elements:
${array[@]}(separate) or${array[*]}(one string) - Array Length:
${#array[@]}(number of elements) - Element Length:
${#array[index]}(length of specific element) - Modify:
array[index]=value - Add:
array+=(new items)orarray+=("new") - Remove:
unset array[index](creates sparse array) - Iterate:
for item in "${array[@]}"; do ... done - Indices:
${!array[@]}gets all indices - Associative:
declare -A arraythenarray[key]=value - Always quote: Use
"${array[@]}"to preserve spaces
What's Next?
Perfect! You've mastered arrays in Bash. Now you're ready to move on to Strings & Text Processing. You'll learn about string operations, parameter expansion for pattern matching, and here documents - essential tools for text manipulation and data processing in Bash!
Enjoying these tutorials?