Loops

Like any other programming language, Bash supports loops.

The loops are used to repeatedly execute a set of commands based on some condition.

With Bash you can use for loops, while loops, and until loops.

For Loop

The for loop operates on lists of items. It repeats a set of commands for every item in a list.

#/bin/bash
for <var> in <value1 value2 ... valuen>
do
   <command 1>
   <command 2>
   <etc>
done

Example

#!/bin/bash 

users="bobby tony" 

for user in ${users} 

do 
echo "${user}" 
done

While Loop

A while loop is a statement that iterates over a block of code till the condition specified is evaluated to false.

Example:

Until Loop

The until loop is executed as many times as the condition/command evaluates to false.

The loop terminates when the condition/command becomes true.

Example:

Last updated