Working with WHILE Loop in Bash Shell Scripting
Abstract: /bin/bashecho $i
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.
Syntax: while [ condition ]do
// programme to execute
done
For example following loop will be executed 10 times and exited when value of i will be greater than 10.
#!/bin/bash i=1 while [ $i -le 10 ] do echo "This is looping number $i" let i++ doneInfinite 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.
#!/bin/bash while true do 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.
#!/bin/bash while true do if [ condition ];do exit fi doneC-Style while Loop
In bash script we can also write while loops pretty similar to c programming language.
#!/bin/bash i=1 while((i <= 10)) do echo $i let i++ doneReading 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 i do echo $i done < /tmp/filename.txt
In this while loop read one line from file in one loop iteration and store value in variable i.