Leaving a loop early
Sometimes when you are coding a script, you encounter a situation where you would like to exit the loop early, before the ending condition is met. This can be accomplished using the break
and continue
commands.
Here is a script that shows these commands. I am also introducing the sleep
command which will be talked about in detail in the next script.
Chapter 3 - Script 9
#!/bin/sh # # 5/3/2017 # echo "script9 - Linux Scripting Book" FN1=/tmp/break.txt FN2=/tmp/continue.txt x=1 while [ $x -le 1000000 ] do echo "x:$x" if [ -f $FN1 ] ; then echo "Running the break command" rm -f $FN1 break fi if [ -f $FN2 ] ; then echo "Running the continue command" rm -f $FN2 continue fi let x++ sleep 1 done echo "x:$x" echo "End of script9" exit 0
Here's the output from my system:
Run this on your system, and in another terminal cd
to the /tmp
directory. Run the command touch continue.txt
and watch what happens. If you like you can do this multiple times (remember...