Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Linux Shell Scripting Bootcamp

You're reading from   Linux Shell Scripting Bootcamp The fastest way to learn Linux shell scripting

Arrow left icon
Product type Paperback
Published in Jul 2017
Publisher Packt
ISBN-13 9781787281103
Length 208 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
James K Lewis James K Lewis
Author Profile Icon James K Lewis
James K Lewis
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Getting Started with Shell Scripting FREE CHAPTER 2. Working with Variables 3. Using Loops and the sleep Command 4. Creating and Calling Subroutines 5. Creating Interactive Scripts 6. Automating Tasks with Scripts 7. Working with Files 8. Working with wget and curl 9. Debugging Scripts 10. Scripting Best Practices Index

Leaving a loop early


Sometimes when you are coding a script, you encounter a situation where you would like to exit the loop early, before the ending condition is met. This can be accomplished using the break and continue commands.

Here is a script that shows these commands. I am also introducing the sleep command which will be talked about in detail in the next script.

Chapter 3 - Script 9

#!/bin/sh
#
# 5/3/2017
#
echo "script9 - Linux Scripting Book"

FN1=/tmp/break.txt
FN2=/tmp/continue.txt

x=1
while [ $x -le 1000000 ]
do
 echo "x:$x"
 if [ -f $FN1 ] ; then
  echo "Running the break command"
  rm -f $FN1
  break
 fi

 if [ -f $FN2 ] ; then
  echo "Running the continue command"
  rm -f $FN2
  continue
 fi

 let x++
 sleep 1
done

echo "x:$x"

echo "End of script9"

exit 0

Here's the output from my system:

Run this on your system, and in another terminal cd to the /tmp directory. Run the command touch continue.txt and watch what happens. If you like you can do this multiple times (remember...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime