Chapter 59: Bash Arrays
Bash Arrays
This is one of the most powerful features in Bash scripting — and also one that confuses beginners the most at first. But once you get it, arrays become your best friend for handling lists of things — files, names, numbers, folders, colors, anything you want to keep together and loop over.
So let’s learn it like we’re sitting together in Hyderabad — slow, clear, step-by-step, with lots of real examples you can type right now.
What is a Bash Array? (Super Simple Answer)
A Bash array is just a single variable that can hold many values at the same time — like a tray with many small cups instead of one big cup.
Instead of:
|
0 1 2 3 4 5 6 7 8 |
city1="Hyderabad" city2="Delhi" city3="Mumbai" |
You make one array variable:
|
0 1 2 3 4 5 6 |
cities=("Hyderabad" "Delhi" "Mumbai" "Bangalore" "Chennai") |
Now you have five values inside one variable — and you can easily loop over them, add more, remove, change, etc.
Two Types of Arrays in Bash
- Indexed arrays (normal lists — numbered 0, 1, 2…) → Most common, available in all Bash versions
- Associative arrays (key-value pairs — like dictionary/map) → Need Bash 4+ (almost all systems in 2026 have it)
1. Indexed Arrays – The Most Used Type
How to Create an Indexed Array
Three common ways:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Way 1 – Most readable (recommended) fruits=(apple banana "mango shake" orange kiwi) # Way 2 – One by one (useful when building dynamically) colors[0]="red" colors[1]="blue" colors[2]="green" colors[5]="yellow" # gaps are allowed – index 3 & 4 are empty # Way 3 – From command output files=($(ls *.txt)) # careful – bad if filenames have spaces # better way: mapfile -t files < <(ls *.txt) # safe for spaces & special chars |
How to Access Elements
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
echo ${fruits[0]} # first item → apple echo ${fruits[1]} # second → banana echo ${fruits[2]} # mango shake (spaces preserved) echo ${fruits[@]} # all elements (space separated) echo "${fruits[@]}" # all elements – safest (keeps spaces) echo ${#fruits[@]} # number of elements → 5 echo ${!fruits[@]} # all indexes → 0 1 2 3 4 |
Golden rule: Always quote “${array[@]}” when looping or passing to commands — otherwise spaces break things.
Loop Over an Array (Very Common)
|
0 1 2 3 4 5 6 7 8 9 |
for fruit in "${fruits[@]}" do echo "I like $fruit very much!" done |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 |
I like apple very much! I like banana very much! I like mango shake very much! I like orange very much! I like kiwi very much! |
Add / Modify / Remove Elements
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Add at the end (append) fruits+=("pineapple") # Add at specific index fruits[10]="grapes" # creates gap if needed # Replace element fruits[1]="strawberry" # Remove element unset fruits[3] # removes orange (index 3) # Remove whole array unset fruits |
2. Associative Arrays – Key → Value (Like Dictionary)
Need Bash 4+ (Ubuntu 18.04+, Fedora, etc. — all fine in 2026)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# Must declare -A declare -A person person[name]="Priya" person[city]="Hyderabad" person[age]=28 person[skills]="Bash Python AWS DevOps" # Access echo "Name: ${person[name]}" echo "City: ${person[city]}" echo "Skills: ${person[skills]}" # All keys echo "Keys: ${!person[@]}" # All values echo "Values: ${person[@]}" # Number of items echo "Total info: ${#person[@]}" # Loop over key-value for key in "${!person[@]}" do echo "$key → ${person[$key]}" done |
3. Real-Life Useful Script with Arrays (Type This Now!)
Create organize_files.sh:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#!/bin/bash # Array of file types & their destination folders declare -A destinations destinations[".jpg"]="$HOME/Pictures" destinations[".png"]="$HOME/Pictures" destinations[".pdf"]="$HOME/Documents" destinations[".txt"]="$HOME/Documents/text" destinations[".sh"]="$HOME/Scripts" echo "Organizing files in current folder..." for file in * # loop over all files in current dir do if [[ -f "$file" ]]; then # only regular files ext="${file##*.}" # get extension ext=".${ext,,}" # lowercase if [[ -n "${destinations[$ext]}" ]]; then dest="${destinations[$ext]}" if [[ ! -d "$dest" ]]; then mkdir -p "$dest" echo "Created folder: $dest" fi mv -v "$file" "$dest/" echo "Moved $file → $dest" else echo "Skipping $file — no rule for .$ext" fi fi done echo "Organization finished! 🎉" |
Run it in a folder with mixed files:
|
0 1 2 3 4 5 6 7 |
chmod +x organize_files.sh ./organize_files.sh |
It will automatically move files to correct folders!
Summary Table – Bash Arrays Cheat Sheet
| Feature | Indexed Array Example | Associative Array Example |
|---|---|---|
| Declare | fruits=(apple banana) | declare -A person |
| Add element | fruits+=(kiwi) | person[city]=”Hyderabad” |
| Access one element | ${fruits[1]} | ${person[name]} |
| All elements | “$$ {fruits[@]}” | ” $${person[@]}” |
| All indexes/keys | ${!fruits[@]} | ${!person[@]} |
| Number of elements | ${#fruits[@]} | ${#person[@]} |
| Loop | for f in “$$ {fruits[@]}”; do … done | for k in ” $${!person[@]}”; do … done |
| Bash version needed | All versions | Bash 4+ |
Got it, boss? Arrays let you handle lists and collections in Bash — loop over files, store user info, group related data, organize downloads — endless uses.
Any part confusing? Want next:
- “Teacher, explain array tricks (${array[@]:start:length}, etc.)”
- “How to pass arrays to functions”
- “Sort & filter arrays”
- “Read array from file / command output”
- “Common array mistakes & how to debug”
Just say — teacher is ready in Hyderabad! Keep playing with arrays in small scripts — soon you’ll use them everywhere! 🐧📋🔢 😄
