Similar to for loop, while loop is also entry restricted loop. It means condition is checked before executing while loop. Mostly it also can do all the works which for loop can do but in uses it has own benefit of use in programming.
// programme to execute
While Loop Example in Bash
For example following loop will be executed 10 times and exited when value of
i=1 while [ $i-le 10] do echo " This is looping number $i" let i++done
Infinite While Loop in Bash
Infinite for loops can be also known as never ending loop. The following loop will execute continuously until stopped forcefully using CTRL+C.
truedo echo " Press CTRL+C to Exit" done
But we can conditional statement like if to terminate loop on matching any specific condition. Read more about working with if-else in bash scripting.
truedo if [ condition ];do exit fi done
C-Style while Loop
In bash script we can also write while loops pretty similar to c programming language.
i=1 while(( i<= 10)) do echo $ilet i++done
Reading File Content using While Loop
While also provide option’s to read file content line by line, which is an very useful uses of while loop while working with files.
#!/bin/bash while read
ido echo $idone < /tmp/filename.txt
In this while loop read one line from file in one loop iteration and store value in variable