You need to add “&&” between the two condition inside the square box.
#!/bin/bash # multiple conditions count=1 bore=0 while [ $count -le 8 ] && [ $bore == 0 ]; do echo "$count" sleep 1 (( count++ )) if [ $count == 5 ]; then bore=1 fi done
In the above output there are two conditions exists one is count variable should be less than and also the bore variable should be equal to zero. Hence one of the condition inside while loop turns false loops exits the execution flow. Hence the sample output will be as follows:
[root@rhel1 tmp]# sh while_example.sh 1 2 3 4 [root@rhel1 tmp]#
Also you can use -a instead of “&&” with the same code to get the same output as below:
#!/bin/bash # multiple conditions count=1 bore=0 while test $count -le 8 -a $bore == 0 ; do echo "$count" sleep 1 (( count++ )) if [ $count == 5 ]; then bore=1 fi done
4. While loop with break statement.
You can use break statement to skip the execution flow of the while loop. In the given below example we have accomplished same result using break statement. Here execution flow get into break flow once the bore variable become 1 and it ends execution flow.
#!/bin/bash # Break condition count=1 bore=0 while [ $count -le 8 ]; do echo "$count" sleep 1 (( count++ )) if [ $count == 5 ]; then bore=1 fi if [ $bore -eq 1 ] then break fi done
[root@rhel1 tmp]# sh while_example3.sh 1 2 3 4 [root@rhel1 tmp]#
Leave a Reply