Debug School

rakesh kumar
rakesh kumar

Posted on

Bash Loop

Bash For Loop

Bash While Loop

Bash Until Loop

====================================

Bash For Loop

Basic 'For Loop' Example
for learn in $learn

For Loop to Read a Range
for num in {1..10}

For Loop to Read a Range with Increment/Decrement
for num in {1..10..1}

For Decreament
for num in {10..0..1}

For Loop to Read Array Variables
for i in "${arr[@]}"
For Loop to Read white spaces in String as word separators
for i in $str;

For Loop to Read each line in String as a word
for word in "$str";

For Loop to Read Three-expression
for ((i=1; i<=10; i++))

For Loop with a Break Statement
for table in {2..100..2}

For Loop with a Continue Statement
if [[ $i -gt 5 && $i -lt 16 ]];

Infinite Bash For Loop
for (( ; ; ))

Bash While Loop

while [[ $snum -le $enum ]];

While Loop with Multiple Conditions
Infinite While Loop
While Loop with a Break Statement(while [ $i -ge 1 ] )
While Loop with a Continue Statement(while [ $i -le 10 ] )

Bash Until Loop

until [ $i -gt 10 ]
until [[ $a -gt $max || $b -gt $max ]];

In this topic, we will understand the usage of for loop in Bash scripts.

Like any other programming language, bash shell scripting also supports 'for loops' to perform repetitive tasks. It helps us to iterate a particular set of statements over a series of words in a string, or elements in an array. For example, you can either run UNIX command (or task) many times or just read and process the list of commands using a 'for loop'.

Syntax of For Loop
We can apply 'for loop' on bash script in two ways. One way is 'for-in' and another way is the c-style syntax. Following is the syntax of 'for loop' in bash shell scripting:

for variable in list  
do  
commands  
done  
Enter fullscreen mode Exit fullscreen mode

Or

for (( expression1; expression2; expression3 ))  
do  
commands  
done 
Enter fullscreen mode Exit fullscreen mode

There are some key points of 'for loop' statement:

  1. Each block of 'for loop' in bash starts with 'do' keyword followed by the commands inside the block. The 'for loop' statement is closed by 'done' keyword.
  2. The number of time for which a 'for loop' will iterate depends on the declared list variables.
  3. The loop will select one item from the list and assign the value on a variable which will be used within the loop.
  4. After the execution of commands between 'do' and 'done', the loop goes back to the top and select the next item from the list and repeat the whole process.
  5. The list can contain numbers or string etc. separated by spaces. Some of the 'for loop' examples are given below to illustrate how do they work:

Basic 'For Loop' Example
Bash Script

#!/bin/bash  
#This is the basic example of 'for loop'.  

learn="Start learning from Javatpoint."  

for learn in $learn  
do  
echo $learn  
done  

echo "Thank You."  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop to Read a Range
Bash Script

`#!/bin/bash  
#This is the basic example to print a series of numbers from 1 to 10.  

for num in {1..10}  
do  
echo $num  
done  

echo "Series of numbers from 1 to 10." ` 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop to Read a Range with Increment/Decrement
We can increase or decrease a specified value by adding two another dots (..) and the value to step by, e.g., {START..END..INCREMENT}. Check out the example below:

For Increment

#!/bin/bash  

#For Loop to Read a Range with Increment  

for num in {1..10..1}  
do  
echo $num  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Decreament

#!/bin/bash  

#For Loop to Read a Range with Decrement  

for num in {10..0..1}  
do  
echo $num  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop to Read Array Variables
We can use 'for loop' to iterate the values of an array.

The syntax can be defined as:

array=(  "element1" "element 2" .  .  "elementN" )  

for i in "${arr[@]}"  
do  
echo $i  
done  
Enter fullscreen mode Exit fullscreen mode

Output

For each element in 'array', the statements or set of commands from 'do' till 'done' are executed. Each element could be accessed as 'i' within the loop for the respective iteration. Check out the example below explaining the use of 'for loop' to iterate over elements of an array:

Bash Script

#!/bin/bash  

#Array Declaration  
arr=( "Welcome""to""Javatpoint" )  

for i in "${arr[@]}"  
do  
echo $i  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop to Read white spaces in String as word separators
The syntax can be defined as below:

!/bin/bash

for word in $str;

do



done

Here, str refers to a string.

The statements from 'do' till 'done' are executed for each 'word' of a string. Check out the example below:

Bash Script

!/bin/bash

For Loop to Read white spaces in String as word separators

str="Let's start  
learning from Javatpoint."  

for i in $str;  
do  
echo "$i"  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop to Read each line in String as a word
The syntax can be defined as below:

#!/bin/bash  

for word in "$str";  
do  
<Statements>  
done  
Enter fullscreen mode Exit fullscreen mode

Here, the statements from 'do' till 'done' are executed for each 'line' of a string. Check out the example below:

Bash Script

#!/bin/bash  
#For Loop to Read each line in String as a word  

str="Let's start  
learning from   
Javatpoint."  

for i in "$str";  
do  
echo "$i"  
done  
Enter fullscreen mode Exit fullscreen mode

Image description

For Loop to Read Three-expression
Three expression syntax is the most common syntax of 'for loop'. The first expression refers to the process of initialization, the second expression refers to the termination, and the third expression refers to the increment or decrement.

Check out the example below to print 1 to 10 numbers using three expressions with for loop:

Bash Script

#!/bin/bash  
#For Loop to Read Three-expression  

for ((i=1; i<=10; i++))  
do  
echo "$i"  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop with a Break Statement
A 'break' statement can be used inside 'for' loop to terminate from the loop.

Bash Script


#!/bin/bash  
#Table of 2  



for table in {2..100..2}  
do  
echo $table  
if [ $table == 20 ]; then  
break  
fi  
done  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

For Loop with a Continue Statement
We can use the 'continue' statement inside the 'for' loop to skip any specific statement on a particular condition. It tells Bash to stop executing that particular iteration of the loop and process the next iteration.

Bash Script

!/bin/bash

Numbers from 1 to 20, ignoring from 6 to 15 using continue statement"

for ((i=1; i<=20; i++));  
do  
if [[ $i -gt 5 && $i -lt 16 ]];  
then  
continue  
fi  
echo $i  
done  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Infinite Bash For Loop
When there is no 'start, condition, and increment' in the bash three expressions for loop, it becomes an infinite loop. To terminate the infinite loop in Bash, we can press Ctrl+C.

Bash Script

#!/bin/bash  

i=1;  
for (( ; ; ))  
do  
sleep 1s  
echo "Current Number: $((i++))"  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Bash While Loop

The bash while loop can be defined as a control flow statement which allows executing the given set of commands repeatedly as long as the applied condition evaluates to true. For example, we can either run echo command many times or just read a text file line by line and process the result by using while loop in Bash.

Syntax of Bash While Loop
Bash while loop has the following format:

while [ expression ];  
do  
commands;  
multiple commands;  
done  
Enter fullscreen mode Exit fullscreen mode

The above syntax is applicable only if the expression contains a single condition.

If there are multiple conditions to include in the expression, then the syntax of the while loop will be as follows:

while [ expressions ];  
do  
commands;  
multiple commands;  
done  
Enter fullscreen mode Exit fullscreen mode

The while loop one-liner syntax can be defined as:

while [ condition ]; do commands; done  
while control-command; do Commands; done  
Enter fullscreen mode Exit fullscreen mode

There are some key points of 'while loop' statement:

  1. The condition is checked before executing the commands.
  2. The 'while' loop is also capable of performing all the work as for 'loop' can do.
  3. The commands between 'do' and 'done' are repeatedly executed as long as the condition evaluates to true.
  4. The arguments for a 'while' loop can be a boolean expression. How it works The while loop is a restricted entry loop. It means that the condition is checked before executing the commands of the while loop. If the condition evaluates to true, the set of commands following that condition are executed. Otherwise, the loop is terminated, and the program control is given to the other command following the 'done' statement.

Bash While Loop Examples
Following are some examples of bash while loop:

While Loop with Single Condition
In this example, the while loop is used with a single condition in expression. It is the basic example of while loop which will print series of numbers as per user input:

Example

#!/bin/bash  
#Script to get specified numbers  

read -p "Enter starting number: " snum  
read -p "Enter ending number: " enum  

while [[ $snum -le $enum ]];  
do  
echo $snum  
((snum++))  
done  

echo "This is the sequence that you wanted."  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

While Loop with Multiple Conditions
Following is an example of while loop with multiple conditions in the expression:

Example

#!/bin/bash  
#Script to get specified numbers  

read -p "Enter starting number: " snum  
read -p "Enter ending number: " enum  

while [[ $snum -lt $enum || $snum == $enum ]];  
do  
echo $snum  
((snum++))  
done  

echo "This is the sequence that you wanted." 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Infinite While Loop
An infinite loop is a loop that has no ending or termination. If the condition always evaluates to true, it creates an infinite loop. The loop will execute continuously until it is forcefully stopped using CTRL+C :

Example

#!/bin/bash  
#An infinite while loop  

while :  
do  
echo "Welcome to Javatpoint."  
done  
We can also write the above script in a single line as:

#!/bin/bash  
#An infinite while loop  

while :; do echo "Welcome to Javatpoint."; done  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Here, we have used the built-in command (:) which always return true. We can also use the built-in command true to create an infinite loop just as below:

Example

#!/bin/bash  
#An infinite while loop  

while true  
do  
echo "Welcome to Javatpoint"  
done  
Enter fullscreen mode Exit fullscreen mode

This bash script will also provide the same output as an above infinite script.

Note: Infinite loops can be terminated by using CTRL+C or by adding some conditional exit within the script.
While Loop with a Break Statement
A break statement can be used to stop the loop as per the applied condition. For example:

Example

#!/bin/bash  
#While Loop Example with a Break Statement  

echo "Countdown for Website Launching..."  
i=10  
while [ $i -ge 1 ]  
do  
if [ $i == 2 ]  
then  
    echo "Mission Aborted, Some Technical Error Found."  
    break  
fi  
echo "$i"  
(( i-- ))  
done  
Enter fullscreen mode Exit fullscreen mode

Output

According to the script, the loop is assigned to iterate for ten times. But there is a condition after eight times of iteration which will break the iteration and terminate the loop. The following output will be shown after executing the script.

Image description

While Loop with a Continue Statement
A continue statement can be used to skip the iteration for a specific condition inside the while loop.

Example

#!/bin/bash  
#While Loop Example with a Continue Statement  

i=0  
while [ $i -le 10 ]  
do  
((i++))  
if [[ "$i" == 5 ]];  
then  
    continue  
fi  
echo "Current Number : $i"  
done  

echo "Skipped number 5 using Continue Statement."  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

While Loop with C-Style
We can also write while loop in bash script as similar as a while loop in C programming language.

Example

#!/bin/bash  
#While loop example in C style  

i=1  
while((i <= 10))  
do  
echo $i  
let i++  
done  
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Bash Until Loop

In this topic, we have defined how to use until loop statement in Bash Script.

The while loop is a great option to execute a set of commands when some condition evaluates to true. Sometimes, we need to execute a set of commands until a condition evaluates to true. In such cases, Bash until loop is useful.

Bash Until Loop in a bash scripting is used to execute a set of commands repeatedly based on the boolean result of an expression. The set of commands are executed only until the expression evaluates to true. It means that when the expression evaluates to false, a set of commands are executed iteratively. The loop is terminated as soon as the expression evaluates to true for the first time.

In short, the until loop is similar to the while loop but with a reverse concept.

Syntax
The syntax of until loop looks almost similar to the syntax of bash while loop. But there is a big difference in the functionalities of both. The syntax of bash until loop can be defined as:

until [ expression ];  
do  
command1  
command2  
. . .  
. . . .   
commandN  
done  
Enter fullscreen mode Exit fullscreen mode

If there are multiple conditions in the expression, then the syntax will be as follows:

until [[ expression ]];  
do  
command1  
command2  
. . .  
. . . .   
commandN  
done  
Enter fullscreen mode Exit fullscreen mode

Some of the key points of until loop are given below:

  1. The condition is checked before executing the commands.
  2. The commands are only executed if the condition evaluates to false.
  3. The loop is terminated as soon as the condition evaluates to true.
  4. The program control is transferred to the command that follows the 'done' keyword after the termination.
    The while loop vs. the until loop

  5. The 'until loop' commands execute until a non-zero status is returned.

  6. The 'while loop' commands execute until a zero status is returned.

  7. The until loop contains property to be executed at least once.

  8. Examples of Bash Until Loop
    Following are some examples of bash until loop illustrating different scenarios to help you understand the usage and working of it:

Until Loop with Single Condition
In this example, the until loop contains a single condition in expression. It is the basic example of until loop which will print series of numbers from 1 to 10:

Example

#!/bin/bash  
#Bash Until Loop example with a single condition  

i=1  
until [ $i -gt 10 ]  
do  
echo $i  
((i++))  
done 
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Until Loop with Multiple Conditions
Following is an example with multiple conditions in an expression:

Example

#!/bin/bash  
#Bash Until Loop example with multiple conditions  

max=5  
a=1  
b=0  

until [[ $a -gt $max || $b -gt $max ]];  
do  
echo "a = $a & b = $b."  
((a++))  
((b++))  
done  
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)