How to write infinite loop in Bash using for or while statement
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 ~]#


about 2 years ago
Simplified yet readable version of same example:
#!/bin/bash
i=1
while [ "$i" != "10" ];
do
i=`expr $i + 1`
echo loop $i
done
echo end of shell script
about 2 years ago
More simplified example can be
for i in `seq 1 10`; do echo loop $i; done
Output:
nick@nick-desktop ~$ for i in `seq 1 10`; do echo loop $i; done
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10
nick@nick-desktop ~$
In the above example, “seq” command is used to generate a sequence of numbers with start and end limits.