Bash

Bash while loop

Bash while loop

While Loop in Bash

Just like for loop, while loop is additionally entry restricted loop. It determines the condition is reviewed before executing the while loop. While loop is additionally capable to try to do all the work as for loop can do.

Syntax:

while [condition]

do

 //programme to execute

done

Example 1:

This example will simply be demonstrating of while loop that it can also be considered while writing our code or script instead of for loop.

Code/ script

#!/bin/bash
 
num=1
while [ $num -le 5 ]
do
   echo "$num"
   let num++
done

Output of the 1st while looped script
Text

Description automatically generated

Infinite While loop

Infinite for loops are often also referred to as a never-ending loop. the subsequent loop will execute continuously until stopped forcefully using CTRL+C.

Infinite while loop script

 
#!/bin/bash
 
while true
do
  echo "Press CTRL+C to Exit"
done


A picture containing graphical user interface

Description automatically generated

The above Loop can be terminated using a condition as an expression, and syntax to do so is,

#!/bin/bash

while true

do

   if [condition];then

      exit

   fi

done

We can also write while loop as we used to do in c programming language, c is actually easy to learn and most of time we learn c as our 1st language. I hope you know about c, or else you can learn from our website.

Example of c type while loop in bash

 
#!/bin/bash
 
num=1
while((num <= 5))
do
   echo $num
   let num++
done

Output of the c Type while loop.
Graphical user interface, text, email

Description automatically generated

we can also utilize while loops to read a value from some variable.

Here is the syntax.

#!/bin/bash
 
while read myvar
do
   echo $myvar
done < /tmp/filename.txt