Showing results for 
Search instead for 
Do you mean 

break out of loop

SOLVED
Go to Solution
Super Advisor Super Advisor

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
1 ACCEPTED SOLUTIONS
Honored Contributor Honored Contributor

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
4 REPLIES
Super Advisor Super Advisor

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
Honored Contributor Honored Contributor

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
Honored Contributor Honored Contributor

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
Super Advisor Super Advisor

Re: break out of loop

thanks chaps ...

that has cleared some questions.
hello