Skip to Content
Learning Linux Shell Scripting
book

Learning Linux Shell Scripting

by Ganesh Sanjiv Naik
December 2015
Beginner
306 pages
5h 2m
English
Packt Publishing
Content preview from Learning Linux Shell Scripting

Exiting from a loop with a break

In the previous section, we discussed about how continue can be used to exit from the current iteration of a loop. The break command is another way to introduce a new condition within a loop. Unlike continue, however, it causes the loop to be terminated altogether if the condition is met.

In the for_12.sh script, we check the directory's content. If the directory is found, then we are exiting the loop and displaying the message that the first directory is found:

#!/bin/bash
rm -rf sample*
echo > sample_1
echo > sample_2
mkdir sample_3
echo > sample_4

for file in sample*
do
  if [ -d "$file" ]; then
    break;
  fi
done

echo The first directory is $file
rm -rf sample*
exit 0

Let's test the program:

$ chmod +x for_12.sh
$ ./for_12.sh ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Linux Shell Scripting - Second Edition

Learning Linux Shell Scripting - Second Edition

Ganesh Sanjiv Naik

Publisher Resources

ISBN: 9781785286216