HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to BashNumbers & ArithmeticStringsArraysConditions (if)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Arithmetic
✍️ Text
📋 Array
🔁 Condition & Loop
🧩 Functions & Pipes
Bash›Loops (for / while)

Loops (for / while)

Iterating over items/ranges with for and conditional repetition with while.

Simple enough for a 5-year-old to understand

for loop

Example code
1
for i in 1 2 3; do
Every element in the list.
LoopEvery element in the list.
2
echo $i
1, 2, 3
Output / Input1, 2, 3
3
done
LoopOutput / Input
💡 Hint: For ranges: for i in {1..5}; do ... done

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Iterate through the range {1..5} using a for loop and print each number on a new line.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

In Bash, loops mostly iterate over a LIST: file names, lines, arguments. This aligns with the shell's purpose — Bash scripts generally follow the "do this to each of these files" format.

How the list is generated matters. Shell expansion provides file names safely; parsing command output breaks on names containing spaces. The choice between these two determines the script's robustness.

There is another behavior to watch out for: the right side of a pipeline runs in a SUBSHELL. If you modify a variable inside the loop, that change is lost when the loop ends. There is no error message, and the cause is hard to find.

What you will learn

  • iterating over a list with for
  • reading line by line with while
  • what file expansion does when it finds no matches
  • that the pipeline creates a subshell
  • Using break and continue

When to use?

When iterating over files, use direct shell expansion; parsing command output will definitely break on names with spaces.

To read a file line by line, the read command is used and must be called in raw mode so that escape characters are not corrupted.

Common mistakes

Wrong

for f in $(ls *.txt); do
  echo "$f"
done

Since the command output is split into words, "my file.txt" becomes two separate elements and the loop runs with incorrect values. There is no error message. The shell's own file expansion does not suffer from this issue because each match is given as a separate item.

Correct

for f in *.txt; do
  echo "$f"
done

Wrong

count=0
cat numbers.txt | while read line; do
  count=$((count + 1))
done
echo "Total: $count"

Since the right side of the pipeline runs in a subshell, the increment in the loop is not reflected in the main shell: zero is always printed to the screen. There is no error message and the cause is not obvious. Using redirection keeps the loop in the main shell and the modification is preserved.

Correct

count=0
while read -r line; do
  count=$((count + 1))
done < numbers.txt
echo "Total: $count"

Wrong

for f in *.log; do
  echo "Processing: $f"
done

If there are no matching files, Bash does not expand the pattern and passes THE PATTERN ITSELF as a single element; the loop runs once and prints the text with the asterisk. Checking for file existence or enabling the nullglob option fixes this behavior.

Correct

shopt -s nullglob
for f in *.log; do
  echo "Processing: $f"
done

Frequently asked questions

How do I loop over numbers?

Curly brace range syntax is the shortest way and does not call external programs. If the limits are variables, this syntax does not work because expansion happens BEFORE variable expansion; in that case, the C-style double-parenthesis loop is used.

Why should read be called in raw mode?

Because by default, it treats backslashes as escape characters and destroys them. Raw mode prevents this. Additionally, the field separator variable must be emptied to preserve leading and trailing spaces.

How do I break out of an infinite loop?

The break command terminates the innermost loop, and you can break out of multiple loops by passing a number argument — this is a convenience in Bash that many other languages lack. Meanwhile, continue skips the current step and moves on to the next one.

Summary

When iterating over files, shell expansion is used, command output is not parsed.

The right side of a pipeline runs in a subshell; variable modifications are lost.

Unmatched patterns are not expanded and return themselves.

read must be called in raw mode, otherwise escape characters are destroyed.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code