break out of loop (16 Views)
Reply
Super Advisor
lawrenzo_1
Posts: 560
Registered: ‎06-06-2003
Message 1 of 5 (16 Views)
Accepted Solution

break out of loop

Hi,

I am having sytax difficulty breaking out of a loop:

while read FILES
do

if [ -f archive.gz ] ; then

break

else

for list in `ls $FILES`
do
cat $list >> $outfile
done

done < $dirlist

so funny as it seems dirlist contains a list of directories however if that directory has already been processed I want the script skip cat'ing all files in the dir and continue with the next directory in $dirlist however all that happens is the scripts exits

I am obviously not using break correctly, any idea's?

Thanks

Chris
hello
Please use plain text.
Super Advisor
lawrenzo_1
Posts: 560
Registered: ‎06-06-2003
Message 2 of 5 (16 Views)

Re: break out of loop

looked into this again and realised I dont need break however using "continue" has resolved my issue.

Still I thought break would have the same effect.
hello
Please use plain text.
Honored Contributor
Jeff_Traigle
Posts: 1,354
Registered: ‎03-04-2004
Message 3 of 5 (16 Views)

Re: break out of loop

Based on what you say you want it to do, you simply want to do nothing if the archive.gz file exists and continue processing the remainder of the $dirlist so your code should look something like this:

while read FILES
do

if [ ! -f archive.gz ]
then

for list in `ls $FILES`
do
cat $list >> $outfile
done

done < $dirlist


As for the break command, it's doing exactly what it's supposed to do. Per the sh-posix(1) man page:

% break [n] Exit from the enclosing for, select, until, or while loop, if any. If n is specified, exit from n levels.
--
Jeff Traigle
Please use plain text.
Honored Contributor
Ralph Grothe
Posts: 2,631
Registered: ‎04-09-2000
Message 4 of 5 (16 Views)

Re: break out of loop

Hi Chris,

depends on your programming logic.

While "break" would leave the loop immediately
(note, that although you cannot specify labels like in Perl to distinguish which of several nested loops to exit, you may give braek an optional decimal that specifies the n'th level)
a "continue" would simply skip all the remaining execution block of a loop to enter the next iteration.
(needless to mention that "continue" also honours an optional loop level argument like "break").
Madness, thy name is system administration
Please use plain text.
Super Advisor
lawrenzo_1
Posts: 560
Registered: ‎06-06-2003
Message 5 of 5 (16 Views)

Re: break out of loop

thanks chaps ...

that has cleared some questions.
hello
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation