Bash Scripting — Manipulating Arrays
Welcome to Chapter 21 — Manipulating Arrays 🎉
Arrays are one of the most powerful features in Bash scripting. Whether you’re managing a list of servers, processing log entries, or building a configuration tool — arrays keep your data organised and your scripts clean.
In this chapter, we’ll go from the basics of creating and reading arrays all the way through to sorting, slicing, and understanding when arrays beat plain strings.
What You’ll Learn
| # | Topic | What’s Covered |
|---|---|---|
| 1 | Indexed Array CRUD | Create, read, update, delete elements in indexed arrays |
| 2 | Associative Array CRUD | Key-value pairs with declare -A, iteration, existence checks |
| 3 | Array Slicing and Copying | Sub-arrays, appending, deduplication, array ↔ string |
| 4 | Sorting Arrays | mapfile + sort, numeric sort, reverse, sort by field |
| 5 | Array vs String Performance | When to reach for arrays, word-splitting traps, nameref passing |
| 6 | Practice Exercises | 5 hands-on challenges from easy to advanced |
Prerequisites
Before diving in, make sure you’re comfortable with:
- Basic Bash syntax (variables, quoting, loops)
- Running scripts from the terminal
- The difference between
$varand"$var"(quoting matters!)
If you need a refresher, revisit the earlier chapters on variables and loops.
Indexed vs Associative Arrays — Quick Overview
Bash supports two kinds of arrays:
Indexed Arrays
Elements are stored by numeric position (starting at 0).
fruits=("apple" "banana" "cherry")
echo "${fruits[1]}" # banana
Associative Arrays
Elements are stored by string keys (like a dictionary or hash map). You must declare them with declare -A.
declare -A colours
colours[sky]="blue"
colours[grass]="green"
echo "${colours[sky]}" # blue
Key Differences at a Glance
| Feature | Indexed | Associative |
|---|---|---|
| Declaration | arr=() or declare -a |
declare -A |
| Keys | Integers (0, 1, 2…) | Arbitrary strings |
| Order | Insertion order preserved | No guaranteed order |
| Bash version | 3.0+ | 4.0+ |
💡 Tip: Run
bash --versionto check. Most modern Linux distros ship with Bash 5.x. macOS ships with Bash 3.2 by default — install a newer version via Homebrew if you need associative arrays.
How This Chapter Is Organised
Each lesson follows a consistent pattern:
- Concept — a short explanation with a diagram or table
- Script — a complete, runnable example with
#!/usr/bin/env bashandset -euo pipefail - Expected output — so you can verify your results
- Mini-exercise — a quick challenge to reinforce the concept
The final lesson is a dedicated set of practice exercises that tie everything together.
Let’s Get Started!
Head over to Indexed Array CRUD to begin working with arrays right away.
Happy scripting! 🚀