Loops plays an important role in bash scripting. After For Loop another loop comes in to picture is Bash while loop. Basically Bash while loop executes sets of command till any condition is satisfied. Once condition turns false execution flow gets out of the bash while loop.
Basic syntax of “Bash while loop”:
while [ <condition> ] do <command1> <command2> . <commandN> done
Let’s move on to the bash while loop examples.
Bash while loop examples.
1. Simple while loop.
[root@rhel1 mann]$ cat while_exp1.sh #!/bin/bash # Simple bash while loop i="0" while [ $i -lt 4 ] do echo "Welcome to UxTechno $i times" i=$[$i+1] done [root@rhel1 mann]$chmod +x while_exp1.sh
In the above example execution flow continues to echo welcome message till the value of i variable is less than 4. Once the value becomes 4 execution flow exits the loop.
2. Infinite while loop:
[root@rhel1 mann]$ cat while_exp2.sh #!/bin/bash # Simple bash while loop i="0" while [ $i -lt 4 ] do echo "Welcome to UxTechno $i times" done [root@rhel1 mann]$chmod +x while_exp2.sh
You can make the example for simple bash while loop by just removing the line “i=$[$i+1]” which basically increments the value of variable $i. Hence the condition of value of i variable always remains less than 4 which results in infinite bash while loop.
3.Multiple condition while loop:
You can also use multiple condition inside bash while loop.
Leave a Reply