Looping Through Arrays

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 100 of 205

Most work with arrays happens inside a loop: checking every server in a list, processing every file, adding up every number. Bash offers two main ways to walk an array. A loop over the values gives each element in turn. A loop over the indexes gives each position, from which the value can be read and also changed. This lesson covers both, explains which to choose, and shows the patterns that build on them: changing elements, filtering into a new array, walking two arrays side by side, and stopping early.

Looping Over Values

The standard form passes the quoted expansion "${arr[@]}" to a for loop (lesson 78):

servers=("web 01" db cache)
for s in "${servers[@]}"; do
    echo "checking [$s]"
done
checking [web 01]
checking [db]
checking [cache]

"${arr[@]}" expands to one word per element, so the loop runs once per element and s holds each value exactly as stored, spaces included. This form also handles sparse arrays correctly, because it lists only the elements that exist.

Why the Quotes Are Required

The two other spellings look similar and give wrong results:

for s in ${servers[@]}; do echo "[$s]"; done
[web]
[01]
[db]
[cache]
for s in "${servers[*]}"; do echo "[$s]"; done
[web 01 db cache]

Unquoted ${servers[@]} is split again on whitespace (and glob-expanded), so web 01 became two passes. Quoted "${servers[*]}" joins everything into a single string, so the loop ran only once. Only "${arr[@]}" gives one pass per element.

Looping Over Indexes

"${!arr[@]}" expands to the list of indexes that are in use. Looping over it gives access to both the position and the value:

for i in "${!servers[@]}"; do
    echo "$i: ${servers[i]}"
done
0: web 01
1: db
2: cache

Inside the brackets, the index is arithmetic, so ${servers[i]} works without a $ before i (lesson 98). The index loop is the right choice when you need the position, for example to number the output from 1:

for i in "${!servers[@]}"; do
    printf '%d) %s\n' "$((i + 1))" "${servers[i]}"
done
1) web 01
2) db
3) cache

C-Style Loops and Sparse Arrays

A counting loop (lesson 79) from 0 to the number of elements is common in scripts written by programmers coming from other languages:

for (( i = 0; i < ${#arr[@]}; i++ )); do
    echo "${arr[i]}"
done

It works only when the indexes are exactly 0, 1, 2, ... with no gaps. On a sparse array, such as one where elements were removed with unset (lesson 99), it reads the wrong positions:

sp=([0]=a [3]=d [7]=h)
for (( i = 0; i < ${#sp[@]}; i++ )); do echo "i=$i [${sp[i]}]"; done
i=0 [a]
i=1 []
i=2 []

The array has 3 elements, so the loop visited indexes 0, 1 and 2, found nothing at 1 and 2, and never reached d and h. Looping over "${!sp[@]}" visits exactly the indexes in use:

for i in "${!sp[@]}"; do echo "i=$i [${sp[i]}]"; done
i=0 [a]
i=3 [d]
i=7 [h]

Use the C-style loop only when you need something the index list cannot give, such as walking backward or stepping by two, and only on arrays you know have no gaps (renumber with arr=("${arr[@]}") first if in doubt).

Walking Backward

Counting down from the last index is one of those cases:

vals=(4 17 9 23 2)
for (( i = ${#vals[@]} - 1; i >= 0; i-- )); do
    printf '%s ' "${vals[i]}"
done
echo
2 23 9 17 4 

Changing Elements Inside a Loop

The loop variable of a value loop holds a copy of each element. Changing it does not change the array:

nums=(1 2 3)
for n in "${nums[@]}"; do n=$(( n * 10 )); done
declare -p nums
declare -a nums=([0]="1" [1]="2" [2]="3")

To change the array itself, loop over the indexes and assign to arr[i]:

for i in "${!nums[@]}"; do
    nums[i]=$(( nums[i] * 10 ))
done
declare -p nums
declare -a nums=([0]="10" [1]="20" [2]="30")

Inside $(( )), array elements can also be written without $ and braces, as nums[i].

Adding Elements During a Loop

The list that a for loop walks is expanded once, before the first pass. Elements added to the array inside the loop are not visited by the same loop:

w=(1 2 3)
for x in "${w[@]}"; do
    w+=("$x$x")
    echo "saw $x"
done
declare -p w
saw 1
saw 2
saw 3
declare -a w=([0]="1" [1]="2" [2]="3" [3]="11" [4]="22" [5]="33")

The loop ran three times even though the array grew to six elements. This makes it safe to append while looping, and it also means that a work list which must process items added on the way needs a while loop that checks the array each time, like the queue in lesson 99.

Building a New Array from a Loop

Filtering is a loop that appends matching elements to a new array:

files=(report.txt photo.jpg notes.txt song.mp3)
txt=()
for f in "${files[@]}"; do
    [[ $f == *.txt ]] && txt+=("$f")
done
declare -p txt
declare -a txt=([0]="report.txt" [1]="notes.txt")

Starting with txt=() makes sure the result is empty even if a variable with that name existed before. The pattern *.txt on the right of == is unquoted on purpose, so it is matched as a pattern (lesson 70).

Calculating Over All Elements

Totals, maximums and counts follow the same shape: initialize, update in the loop, use the result afterward:

vals=(4 17 9 23 2)
sum=0 max=${vals[0]}
for v in "${vals[@]}"; do
    (( sum += v ))
    (( v > max )) && max=$v
done
echo "sum=$sum max=$max"
sum=55 max=23

The maximum starts from the first element rather than from 0, so the code also works when every value is negative.

Walking Two Arrays Together

Bash has no list of pairs, so related values are often kept in parallel arrays that share the same indexes. One index loop reads both:

names=(Ana Bo Cara)
scores=(91 78 85)
for i in "${!names[@]}"; do
    printf '%-5s %3d\n' "${names[i]}" "${scores[i]}"
done
Ana    91
Bo     78
Cara   85

%-5s prints the name left-aligned in 5 columns and %3d prints the score right-aligned in 3 (lesson 30). Parallel arrays must be kept in step: removing an element from one without removing the same index from the other breaks every pair after it. When the pairs are really names with values, an associative array (lesson 102) is often clearer.

Stopping Early and Skipping Elements

break and continue (lesson 84) work in array loops like in any other loop:

files=(report.txt photo.jpg notes.txt song.mp3)
for f in "${files[@]}"; do
    [[ $f == *.jpg ]] && continue
    [[ $f == *.mp3 ]] && break
    echo "processing $f"
done
processing report.txt
processing notes.txt

photo.jpg was skipped, and the loop ended at song.mp3. A while loop with an index is useful when the loop should stop at the first match and the position of that match is needed afterward:

vals=(4 17 9 23 2)
i=0
while (( i < ${#vals[@]} )); do
    (( vals[i] > 10 )) && { echo "first over 10: ${vals[i]} at $i"; break; }
    (( i++ )) || true
done
first over 10: 17 at 1

The || true after (( i++ )) matters only in scripts with set -e: when i is 0, (( i++ )) returns status 1 (lesson 73), which would end such a script.

Looping Over Part of an Array

A slice (lesson 98) restricts the loop to some of the elements:

for s in "${files[@]:1:2}"; do echo "[$s]"; done
[photo.jpg]
[notes.txt]

This skips a header element, processes items in batches, or leaves out the first value when it has already been handled.

Empty Arrays

A loop over an empty array simply does not run, and its status is 0:

emp=()
for x in "${emp[@]}"; do echo "never"; done
echo "empty loop status $?"
empty loop status 0

In Bash 5.2, this also works in a script with set -u (lesson 120):

set -u
e=()
for x in "${e[@]}"; do :; done
echo "ok under set -u"
ok under set -u

Bash versions before 4.4 treated "${e[@]}" of an empty array as an unset variable under set -u and stopped the script. Scripts that must run on such versions, including Bash 3.2 on macOS, often write ${e[@]+"${e[@]}"}, which expands to nothing when the array is empty.

Lines of a File

Combined with mapfile (lesson 98), an array loop processes a file line by line, with each line kept whole:

printf 'alpha\nbeta gamma\n' > lines.txt
mapfile -t L < lines.txt
for l in "${L[@]}"; do echo "line: [$l]"; done
line: [alpha]
line: [beta gamma]

Reading everything into an array first is convenient when the lines are needed more than once or in a different order. For very large files, a while read loop (lesson 80, and lesson 114) handles one line at a time without keeping the whole file in memory.

Lists of Lists

An element cannot itself be an array (lesson 97). When each item of a list has its own members, a common approach keeps the members in one string per element and splits it inside the loop with read -a:

groups=("a b" "c d e")
for g in "${groups[@]}"; do
    read -r -a members <<< "$g"
    echo "group of ${#members[@]}: ${members[*]}"
done
group of 2: a b
group of 3: c d e

This works when the members never contain the separator, here a space. With a different IFS for read, the members can be separated by commas or colons instead.

Printing an Array Without a Loop

Sometimes a loop is not needed at all. printf repeats its format for every argument, so it prints one element per line, and a subshell with a changed IFS joins the elements with a separator (lesson 98):

printf '%s\n' "${files[@]}" | sort
(IFS=,; echo "${files[*]}")
notes.txt
photo.jpg
report.txt
song.mp3
report.txt,photo.jpg,notes.txt,song.mp3

Piping printf '%s\n' "${arr[@]}" into sort, grep or uniq lets the standard text tools work on an array. The result can be read back into an array with mapfile -t sorted < <(printf '%s\n' "${files[@]}" | sort).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Looping Through Arrays and get answers drawn from it.

Signed-in readers only.