Skip to Main Content
Linux Pocket Guide
book

Linux Pocket Guide

by Daniel J. Barrett
February 2004
Beginner content levelBeginner
200 pages
5h 40m
English
O'Reilly Media, Inc.
Content preview from Linux Pocket Guide

Break and Continue

The break command jumps out of the nearest enclosing loop. Consider this simple script called myscript:

for name in Tom Jack Harry
do
  echo $name
  echo "again"
done
echo "all done"
$ ./myscript
Tom
again
Jack
again
Harry
again
all done

Now with a break:

for name in Tom Jack Harry
do
  echo $name
  if [ "$name" = "Jack" ]
  then
    break
  fi
  echo "again"
done
echo "all done"
$ ./myscript
Tom
again
Jack            The break occurs
all done

The continue command forces a loop to jump to its next iteration.

for name in Tom Jack Harry
do
  echo $name
  if [ "$name" = "Jack" ]
  then
    continue
  fi
  echo "again"
done
echo "all done"
$ ./myscript
Tom
again
Jack          The continue occurs
Harry
again
all done

break and continue also accept a numeric argument (break N, continue N) to control multiple layers of loops (e.g., jump out of N layers of loops), but this kind of scripting leads to spaghetti code and we don’t recommend it.

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

Linux Pocket Guide, 2nd Edition

Linux Pocket Guide, 2nd Edition

Daniel J. Barrett
Linux in a Nutshell, 6th Edition

Linux in a Nutshell, 6th Edition

Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins

Publisher Resources

ISBN: 9780596806347Errata Page