Course


Bash looping statements

Learn about Bash for-loop, while-loop and until

Bash looping statements

The for loop

For loops allow repeated execution of a command sequence based on an iteration variable. Bash supports two kinds of for loop, a “list of values” and a “traditional” c-like method.


for varname in list
do
 commands 
done

Note that

  • Bash for, in, do and done are keywords
  • list contains a list of items, which can be in the statement or fetched from a variable that contains several words separated by spaces.
  • If list is missing from the for statement, then bash uses positional parameters that were passed into the shell.

Example:

Bash (5.0.0)
  • Show Input  

Note the counter increment command $(( i++ )) which increases i by 1, each time called.

Bash c-style for-loop

Bash (5.0.0)
  • Show Input  

Note that the built-in variable $RANDOM generates a random number each time called.

Bash while loop

Bash while allows for repetitive execution of a list of commands, as long as the command controlling the while loop executes successfully (exit status of zero). The syntax is:

while expression
do
 commands
done

Note that

  • while, do, done are keywords
  • Expression is any expression which returns a scalar value
  • Commands between do and done are executed while the provided conditional expression is true.

Example:

Bash (5.0.0)
  • Show Input  

Bash inifinite loop:

It is possible to creat an infinite loop in Bash.

An infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs ("pull the plug"). It may be intentional.

Example:

#!/bin/bash

while :
do
 echo "Do something; hit [CTRL+C] to stop!"
done

For server security, we won't be able to allow to run this code, you can watch our Interactive shell cast below.

  • Screencast Interactive Shell