Repeating Instructions With Loops in Bash
Scripting·3 min read·Jan 1, 2025
In programming, a loop statement is a control structure used to repeat the execution of a set of instructions multiple times until a certain condition is met.
The while loop
The while loop is used to execute a set of instructions specified between the do and done keywords, for as long as the condition remains true.
while [[ condition ]];do instructionsdoneThis structure is often used to create long-running processes or to process data of unknown length.
Note: In programming, the cycle in which a loop executes its instructions — whether partially or completely — is called an iteration. For example, if a loop executes the specified instructions 3 times, we'll say that it performed 3 iterations.
Example
Let's consider this script, that outputs the elements of an array of strings:
#!/bin/bashguests=("John Doe" "James Higgins" "Alice Peterson")total=${#guests[@]}index=0Unlock the CLI & Scripting with Bash module
Learn how to gain advanced control over the OS and automate complex routine tasks prone to manual errors with the CLI and Bash scripting.
You get immediate access to:
- 34 focused lessons across the CLI and Bash
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle