O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 after this line
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 after this line
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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required