Concept

Loops

Definition

A loop is a control-flow construct that executes the same block of code repeatedly, either a known number of times or until a condition changes. Loops are the structural alternative to recursion for expressing repetition: instead of a function calling itself, a single block runs again and again, with the language tracking the iteration state. Nearly every programming language ships at least three loop forms — a counted form (for), a condition-tested-first form (while), and a condition-tested-last form (do-while) — because each suits a different shape of repeated work.

In shell scripting the loop is also the bridge between single-command tools and batch operations: it is how you turn a one-shot command into something that runs across hundreds of files, lines, or hosts.

Why it matters

How it works

A loop has three moving parts: an initializer that sets up state, a condition that decides whether to run another iteration, and a step that updates state between iterations. The counted-loop form (for) bundles all three into one header; the while form keeps the condition explicit and leaves init and step to the body. The do-while form runs the body once before checking the condition, which is the right shape when the work itself produces the value you need to test.

Choosing between loops and recursion comes down to data shape and stack budget. Iterative loops fit linear sequences — arrays, file lines, ranges of integers — and use constant stack space regardless of size. Recursion fits self-similar structures like trees, expression grammars, and divide-and-conquer algorithms, where each subproblem is a smaller version of the same problem. A loop expressing a tree traversal needs an explicit stack data structure; a recursive function expressing a counted iteration wastes stack frames. The right tool follows the data.

Where it goes next

Continue exploring

Tags