While Loop in Bash
Similar to for loop, while loop is also entry restricted loop. It means the condition is checked before executing while loop. While loop is also capable to do all the work as for loop can do.
Syntax:
while [condition] do //programme to execute done
#1. Bash – While Loop Example
For example, the following loop will be executed 5 times and terminated when the value of variable num will be greater than 5.
1 2 3 4 5 6 7 8 | #!/bin/bash num=1 while [ $num -le 5 ] do echo "$num" let num++ done |
#2. Bash – Infinite While Loop
Infinite for loops can be also known as a never-ending loop. The following loop will execute continuously until stopped forcefully using CTRL+C.
1 2 3 4 5 6 | #!/bin/bash while true do echo "Press CTRL+C to Exit" done |
You can also terminate this loop by adding some conditional exit in the script. So whenever the condition goes true, the loop will exit.
1 2 3 4 5 6 7 8 | #!/bin/bash while true do if [condition];then exit fi done |
#3. Bash – C-Style While Loop
You can also write while loop in bash scripts similar to while loop c programming language.
1 2 3 4 5 6 7 8 | #!/bin/bash num=1 while((num <= 5)) do echo $num let num++ done |
#4. Bash – While Loop Read File Content
This is a useful feature provided by while loop to read file content line by line. Using this we can read file line by line and perform some tasks.
1 2 3 4 5 6 | #!/bin/bash while read myvar do echo $myvar done < /tmp/filename.txt |
The while loop reads one line from the file in one iteration and assigned the value to the variable myvar.