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:


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @ webmaster@cyberciti.biz