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.

#/bin/bash
while <condition>
do
   <command 1>
   <command 2>
   <etc>
done

Example:

#!/bin/bash 
read -p "What is your name? " name 

while [[ -z ${name} ]] 

do 
echo "Your name can not be blank. Please enter a valid name!" 
read -p "Enter your name again? " name 
done 
echo "Hi there ${name}"

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.

#/bin/bash
until <condition>
do
   <command 1>
   <command 2>
   <etc>
done

Example:

#!/bin/bash 
count=1 
until [[ $count -gt 10 ]] 
do 
    echo $count ((count++)) 
done

Last updated