How to write infinite loop in Bash
In Category Bash
The while-do-done statement can be used to program an infinite loop in bash. The following sample shows how it can be done.
#!/bin/bash while [ 1 ]; do echo I am in infinite loop. Press Ctrl+C to stop me done
The break statement can be used to exit the while loop. The following sample code breaks away from while loop after iterating 10 times.
#!/bin/bash
i=1
while [ 1 ];
do
i=`expr $i + 1`
echo loop $i
if [ "$i" == "10" ]; then
echo Exiting while loop after iterating $i times
break
fi
done
echo end of shell script
The following will be the output when the above script is run.
[neo@techpulp ~]# sh iloop.sh loop 2 loop 3 loop 4 loop 5 loop 6 loop 7 loop 8 loop 9 loop 10 Exiting while loop after iterating 10 times end of shell script [neo@techpulp ~]#
Recent Comments