---
title: "How do I use arrays in Bash?"
description: "How to create, loop over, add to and measure arrays in Bash, how associative arrays work, and why they fail with the old Bash 3.2 that ships with macOS."
url: https://www.danny.engineering/answer/bash/how-do-i-use-arrays-in-bash
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Bash"]
---

# How do I use arrays in Bash?

## The short answer


Create an array with parentheses, and always expand it as `"${arr[@]}"` with the quotes. That gives you one word per element, even when elements contain spaces.


```bash
fruits=("apple" "blood orange" "pear")

for fruit in "${fruits[@]}"; do
  echo "$fruit"
done

echo "Count: ${#fruits[@]}"
echo "First: ${fruits[0]}"
```


## Why it happens


Bash variables are strings by default. If you put a list in a plain string, such as `files="a.txt my notes.txt"`, the shell can only split it on spaces, so `my notes.txt` turns into two items. Arrays keep each element separate, which is the only safe way to hold a list of file names or arguments.


The expansion syntax is where most bugs come from. `$fruits` on its own gives you only the first element. `${fruits[*]}` joins everything into one string. Unquoted `${fruits[@]}` splits elements on spaces again. Only the quoted `"${fruits[@]}"` keeps every element intact, which is why you will see it everywhere in well-written scripts.


## How to fix it


### Create, read and change indexed arrays


```bash
# Create
ports=(3000 3001 3002)
empty=()
declare -a names   # explicit, optional

# Read
echo "${ports[1]}"          # 3001
echo "${ports[@]}"          # all elements
echo "${#ports[@]}"         # number of elements
echo "${!ports[@]}"         # indexes: 0 1 2
echo "${ports[@]:1:2}"      # slice: 3001 3002

# Change
ports+=(4000)               # append
ports[0]=8080               # replace
unset 'ports[1]'            # remove (leaves a gap in the indexes)
```


Indexes start at 0. Removing an element with `unset` does not renumber the rest, so loop over values with `"${ports[@]}"`, or over `"${!ports[@]}"` when you need the index.


### Loop with the index


```bash
for i in "${!ports[@]}"; do
  echo "$i: ${ports[$i]}"
done
```


### Fill an array from a command


Do not write `arr=($(command))`, which splits on spaces and expands globs. Read line by line instead.


```bash
# Bash 4+
mapfile -t lines < todo.txt

# Works in Bash 3.2 too
lines=()
while IFS= read -r line; do
  lines+=("$line")
done < todo.txt
```


### Pass an array as arguments


Arrays are the cleanest way to build up a command's arguments safely.


```bash
args=(--verbose --output "build dir")
if [[ $DRY_RUN == 1 ]]; then
  args+=(--dry-run)
fi

my-tool "${args[@]}"
```


### Associative arrays (Bash 4+)


Associative arrays map string keys to values. You must declare them with `declare -A` first, otherwise Bash treats the keys as numbers.


```bash
declare -A colours
colours[primary]="blue"
colours["call to action"]="orange"

echo "${colours[primary]}"

for key in "${!colours[@]}"; do
  echo "$key = ${colours[$key]}"
done

if [[ -v colours[primary] ]]; then
  echo "primary is set"
fi
```


Keys come back in no particular order. Sort them yourself if order matters.


### The macOS caveat


macOS still ships Bash 3.2 at `/bin/bash`, because later versions use the GPLv3 licence. Its default interactive shell has been zsh since Catalina. On Bash 3.2, `declare -A` fails with "invalid option", and `mapfile`, `readarray` and negative indexes such as `${arr[-1]}` are missing.


Check the version you are actually running:


```bash
echo "$BASH_VERSION"
```


If you need Bash 4 or later features, install a newer Bash with Homebrew and point your shebang at it with `#!/usr/bin/env bash`, so the first `bash` on the `PATH` is used. Or keep to indexed arrays and `while read` loops so the script works everywhere.


## Common pitfalls

- **Forgetting the quotes.** `for f in ${files[@]}` breaks on any element with a space. Write `"${files[@]}"`.
- **Forgetting the braces.** `$arr[1]` prints the first element followed by the text `[1]`. Write `${arr[1]}`.
- **Using** **`$arr`** **to mean the whole array.** It is only element 0.
- **Exporting arrays.** Bash cannot export arrays to child processes. Pass them as arguments instead.
- **Empty arrays with** **`set -u`****.** Bash versions before 4.4 treat `"${arr[@]}"` on an empty array as an unbound variable error.
- **Running under** **`sh`****.** Arrays are not part of POSIX `sh`. Use a Bash shebang.

## Related reading

- [GNU Bash manual: Arrays](https://www.gnu.org/software/bash/manual/html_node/Arrays.html)
