The break command
Break statement could be used to come out of a loop. The additional execution of the loop stops and the next statement after the done statement is executed. This might be useful whenever the user does not need the while loop to execute indefinite number of times. If the mechanism is not given the execution will remain in the loop forever and possibly, the system might hang. Break command helps to overcome this type of conditions.
Practice 1
The given shell program will find whether the file is available in the directory or not.
# cat > break while true
do
echo "Enter the file name:"
read fname
if [ -f $fname ]
then
echo "File not found"
break else
echo "File found"
fi
echo "Bye"
done
# sh break
Enter the filename:
casefile file found bye
Enter the filename
Case
File not found
#
The given program will accept the filename and search whether file exists in the directory or not. It prompts "file found and gets another filename to search if it is found. It will automatically break from the while loop if the file is not found.