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:

Bash

You make one array variable:

Bash

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

  1. Indexed arrays (normal lists — numbered 0, 1, 2…) → Most common, available in all Bash versions
  2. 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:

Bash

How to Access Elements

Bash

Golden rule: Always quote “${array[@]}” when looping or passing to commands — otherwise spaces break things.

Loop Over an Array (Very Common)

Bash

Output:

text

Add / Modify / Remove Elements

Bash

2. Associative Arrays – Key → Value (Like Dictionary)

Need Bash 4+ (Ubuntu 18.04+, Fedora, etc. — all fine in 2026)

Bash

3. Real-Life Useful Script with Arrays (Type This Now!)

Create organize_files.sh:

Bash

Run it in a folder with mixed files:

Bash

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! 🐧📋🔢 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *