< Previous | Contents | Next >
Breaking Out Of A Loop
bash provides two builtin commands that can be used to control program flow inside loops. The break command immediately terminates a loop, and program control re- sumes with the next statement following the loop. The continue command causes the remainder of the loop to be skipped, and program control resumes with the next iteration of the loop. Here we see a version of the while-menu program incorporating both break and continue:
#!/bin/bash
# while-menu2: a menu driven system information program DELAY=3 # Number of seconds to display results
while true; do
clear
cat <<- _EOF_
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
_EOF_
read -p "Enter selection [0-3] > "
if [[ $REPLY =~ ^[0-3]$ ]]; then if [[ $REPLY == 1 ]]; then
echo "Hostname: $HOSTNAME" uptime
sleep $DELAY
continue
fi
if [[ $REPLY == 2 ]]; then df -h
sleep $DELAY
continue
fi
if [[ $REPLY == 3 ]]; then
if [[ $(id -u) -eq 0 ]]; then
echo "Home Space Utilization (All Users)" du -sh /home/*
else
#!/bin/bash
# while-menu2: a menu driven system information program DELAY=3 # Number of seconds to display results
while true; do
clear
cat <<- _EOF_
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
_EOF_
read -p "Enter selection [0-3] > "
if [[ $REPLY =~ ^[0-3]$ ]]; then if [[ $REPLY == 1 ]]; then
echo "Hostname: $HOSTNAME" uptime
sleep $DELAY
continue
fi
if [[ $REPLY == 2 ]]; then df -h
sleep $DELAY
continue
fi
if [[ $REPLY == 3 ]]; then
if [[ $(id -u) -eq 0 ]]; then
echo "Home Space Utilization (All Users)" du -sh /home/*
else
echo "Home Space Utilization ($USER)" du -sh $HOME
fi
sleep $DELAY
continue
fi
if [[ $REPLY == 0 ]]; then break
fi
else
echo "Invalid entry." sleep $DELAY
fi done
echo "Program terminated."
echo "Home Space Utilization ($USER)" du -sh $HOME
fi
sleep $DELAY
continue
fi
if [[ $REPLY == 0 ]]; then break
fi
else
echo "Invalid entry." sleep $DELAY
fi done
echo "Program terminated."
In this version of the script, we set up an endless loop (one that never terminates on its own) by using the true command to supply an exit status to while. Since true will always exit with a exit status of zero, the loop will never end. This is a surprisingly com- mon scripting technique. Since the loop will never end on its own, it’s up to the program- mer to provide some way to break out of the loop when the time is right. In this script, the break command is used to exit the loop when the “0” selection is chosen. The con- tinue command has been included at the end of the other script choices to allow for more efficient execution. By using continue, the script will skip over code that is not needed when a selection is identified. For example, if the “1” selection is chosen and identified, there is no reason to test for the other selections.