How to Write Bash WHILE-Loops

Commands, syntax, and examples

The Bourne Again Shell logo.

Justindorfman / Wikimedia Commons

A while loop is a programming construct that repeats a given instruction until a specific condition is satisfied. The Bourne Again Shell on Linux supports these loops.

Any Linux distribution that supports BASH (which is most of them) supports this kind of scripting. The Windows Subsystem for Linux also supports BASH.

How to Create a While Loop in BASH

nano on wsl

In your text editor of choice, insert your code. For example:

while [ $x -le 10 ]
echo "Looped $x times"
x=$(( $x + 1 ))

This script does several things, line by line:

  • Line 1: Specifies BASH.
  • Line 2: Sets a variable, x, equal to 1.
  • Line 3: Sets the while condition. In this case, the while condition requires that the variable x must be less than or equal to 10.
  • Lines 4 and 7: Begins the do portion of the loop. As long as the while condition remains active, the do clause iterates. The do block ends with the keyword done. If the while condition hasn't been satisfied, the do block repeats.
  • Lines 5 and 6: Performs the looped task. In this case, the script writes "Looped x times" to the console then adds 1 to the value of x.

Output looks something like this:

bash script output

Considerations for BASH While-Loop Scripting

Despite the occasionally wonky syntax, while loops are conceptually straightforward:

  • The while condition is always a boolean—it's either true or false.
  • You're free to insert any number of commands within a do block.
  • If you don't set a while condition, you'll create an infinite loop, which must be broken with a Ctrl+C interruption.
  • If you embed conditionals (if statements) within a do block, you can approximate some form of sanity checking. For example, if a specific conditional value is met during the loop, the break keyword stops the loop. Likewise, the continue keyword will stop subsequent commands and go back to the start of the loop, incrementing as scripted.