≡ Menu

Bash: Continue In a For / While Loop

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:

Sysadmin because even developers need heroes!!!

Share this tutorial on:
{ 0 comments… add one }
Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: , , , , , , , , , , , , , ,