Bash — Arrays
Indexed arrays
#!/bin/bash
# Create array
fruits=("Apple" "Banana" "Cherry" "Date")
# Access elements
echo "${fruits[0]}" # Apple
echo "${fruits[@]}" # All elements
echo "${#fruits[@]}" # Length: 4
# Add element
fruits+=("Elder")
# Remove element
unset fruits[1]
# Iterate
for fruit in "${fruits[@]}"; do
echo "$fruit"
done
Associative arrays
#!/bin/bash
declare -A ages
ages[Alice]=30
ages[Bob]=25
ages[Charlie]=35
echo "${ages[Alice]}" # 30
echo "${!ages[@]}" # All keys
echo "${ages[@]}" # All values
# Iterate
for name in "${!ages[@]}"; do
echo "$name: ${ages[$name]}"
done
Array operations
#!/bin/bash
arr=(1 2 3 4 5)
# Slice
echo "${arr[@]:1:3}" # 2 3 4
# Replace
echo "${arr[@]/3/99}" # 1 2 99 4 5
# Join
echo "$(IFS=', '; echo "${arr[*]}")" # 1,2,3,4,5
Mini Practice
Write Bash code that:
- Creates and iterates an indexed array
- Creates an associative array
- Slices an array
- Joins array elements with a delimiter
Up Next
In the next lesson, you'll learn about Operators — comparison and logical operators.
Related Topics
Frequently Asked Questions about Arrays
What is Arrays in Bash?
Arrays is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Arrays?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.
Why is Arrays important in Bash?
Arrays is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.