Bash: Continue In a For / While Loop

by on January 29, 2010 · 0 comments· LAST UPDATED January 29, 2011

in

How do I continue in a for or while loop in Bash under UNIX or Linux operating systems?

The continue statement is used to resume the next iteration of the enclosing FOR, WHILE or UNTIL loop.

Bash for Loop continue Syntax

 
for i in something
do
	[ condition ] && continue
	cmd1
	cmd2
done
 

A sample shell script to print number from 1 to 6 but skip printing number 3 and 6 using a for loop:

#!/bin/bash
for i in 1 2 3 4 5 6
do
	### just skip printing $i; if it is 3 or 6  ###
	if [ $i -eq 3 -o $i -eq 6 ]
	then
		continue  ### resumes iteration of an enclosing for loop ###
	fi
        # print $i
	echo "$i"
done

Bash while Loop continue Syntax

while true
do
	[ condition1 ] && continue
	cmd1
	cmd2
done

A sample shell script to print number from 1 to 6 but skip printing number 3 and 6 using a while loop:

#!/bin/bash
i=0
while [ $i -lt 6 ]
do
	(( i++ ))
        ### resumes iteration of an enclosing while loop if $i is 3 or 6 ###
	[ $i -eq 3 -o $i -eq 6 ] && continue
	echo "$i"
done

See also:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: