Skip to main content
Arrays in Bash empower you to store multiple values in an indexed collection, offering direct access to any element—first, middle, or last—by its index. This is analogous to reaching into a specific drawer when you know exactly where your socks are kept, rather than inspecting each one sequentially.
The image illustrates the concept of arrays using a drawer analogy, showing three drawers labeled 1, 2, and 3 on the left, and an array with indices 0, 1, and 2 on the right.
Bash arrays are zero-indexed: the first element is at index 0, the second at 1, and so on.

Why Use Arrays?

  • Direct element access reduces loops and conditional checks.
  • Cleaner scripts when handling lists of servers, filenames, or configurations.
  • Improved performance versus string-based lists requiring manual parsing.
Compare a string-based iteration:
Output:
This checks every item, akin to opening each drawer until you find your socks. Arrays eliminate that overhead.

Declaring Arrays

1. Assigning by Index

The image illustrates an array with three indexed elements (0, 1, 2), highlighting the second element (index 1) as "server[1]".

2. Inline Initialization

You can also omit declare -a:

Accessing Array Elements

Get All Elements


Quoting Arrays: Preserve Whitespace

Unquoted expansions split on spaces:
Output:
Always quote ${array[@]} in loops or commands to preserve elements containing spaces.
Unquoted expansions can lead to unexpected word splitting.

Modifying Arrays

Append an Element

Overwrite Entire Array

Assigning a string replaces index 0 but retains the array type:

Further Reading and References

Watch Video