Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Introduction
  • Continue with conditional statements
  • Continue statement in Bash for loop
  • Purpose of the continue statement
  • Example Script
  • Best practices when using the continue statement

Bash Continue – Using with for Loop

PreviousBash for Loop with ArrayNextBash Backticks vs Dollar Parentheses $()

Last updated 1 year ago

Introduction

A Bash for loop is a control structure that is used to repeat a block of statements a specified number of times. But can Bash allow us to iterate over certain conditions only? We can employ the continue statement in conjunction with the for loop to skip the current iteration of the loop and move on to the next.

Knowing how the for loops work with continue can be useful in situations where we are to selectively execute certain statements within the loop based on certain conditions. The continue statement with for loops can almost be seen practically everywhere- from performing arithmetic operations of certain numbers over a range to file manipulations.

In this tutorial, we will first take a moment to understand what continue actually mean in Bash. We will then focus on how this command can work hand in hand with the for loop. We are also going to write a Bash script to tackle challenging real-world problems

Continue with conditional statements

  • The continue statement in Bash makes the for loop skip the current iteration completely and move on to the next iteration.

  • When the continue statement is encountered within the loop, the remaining statements within the loop for the current iteration are skipped.

  • The loop proceeds immediately to the next iteration.

Syntax

A Bash for loop can be easily integrated with the continue statement to iterate through a list of items and bypass a set of iterations when certain criteria is met.

Here’s the syntax:

for iterator in listdo if [ condition ] then continue fidone

Is continue really continuing?

The continue statement, because of its name, can cause some serious confusion for the ones who are new to programming or Bash scripting.

#!/bin/bashfor i in {1..5}do echo A echo B continue echo C echo Ddone

The keyword "continue" might be misleading. In this example, we are printing A and then B. We then reach the continue statement.

What should we expect? That it should continue to keep on going and print C followed by D? Instead, it interrupts the flow of the code by skipping the remaining two echo statements and starts the next iteration. Hence, we can consider it to be a goto statement for continuing with the next iteration.

Continue statement in Bash for loop

1. In every iteration of the for loop, the iterator grabs the value of every element present one at a time.

2. The logical expression is evaluated for each item in the list.

3. In case the condition becomes true, the code flow reaches the continue statement.

4. Upon the successful execution of the continue statement, Bash ends up skipping the current iteration and selects the next item in the list.

5. In case the condition is false, the set of commands outside the if block are executed.

We can understand this easily with a simple example:

Example:

#!/bin/bashfor i in {1..10}do if (( i % 2 != 0 )) then continue fi echo $idone

In the script, the iterator runs sequentially from 1 to 10. In every iteration, modulus operator (%) determines if the current value of the iterator is even. If it is odd, the continue statement is executed which skips all the commands and the loop moves on to the next iteration.

If it is even, the echo command prints the current value of the iterator on the terminal. Hence, we get all the even numbers between 1 to 10.

Purpose of the continue statement

The continue statement is used in Bash to skip the current iteration of the for loop and jump on to the next one. It controls the flow of the loop and selectively executes certain statements within the loop.

It enables us to skip certain iterations of a loop based on certain conditions. Hence we are free from writing complex nested conditional statements. This makes the script easier to read and interpret at the first glance.

When iterating over a large set of data, we are often required to process a subset of the data. For this the continue statement skips the unwanted data and only handles the relevant one. This reduces the processing time.

Example Script

The continue statement becomes a lifesaver when we are to process data from a large csv file that may contain empty or incomplete records. In this situation, we will use the continue statement to skip over the incomplete and wrong records and only process those that meet our criteria.

Let us consider we have a records file named records.csv with the following contents:

1,England,London,Europe,Pound
2,France,Paris,Europe,Franc
3,Germany,Berlin,Europe
4,UAE,AbuDhabi,Asia,Dirham
5,USA,WashingtonD.C.,North America,Dollar,Chicago
6,Russia,Moscow,Asia/Europe,Rouble

The script will print error statements for those records (lines) in the csv which do not have 5 fields. After splitting the valid entries, we will again do a validation on the country name to ensure it begins with an uppercase character. Finally, we map the valid records to their respective fields.

#!/bin/bash # Set the delimiterDELIM="," # Read the csvfor LINE in $(cat records.csv)do # Split the line into fields using the delimiter totalVars=`echo $LINE | awk -F"$DELIM" '{print NF}'` if [ "$totalVars" != "5" ] then echo "----" echo [ERROR] $LINE # 5 variables cannot be generated continue fi # Split the fields SNO=`echo "$LINE" | awk -F"$DELIM" '{print $1}'` COUNTRY=`echo "$LINE" | awk -F"$DELIM" '{print $2}'` CAPITAL=`echo "$LINE" | awk -F"$DELIM" '{print $3}'` CONTINENT=`echo "$LINE" | awk -F"$DELIM" '{print $4}'` CURRENCY=`echo "$LINE" | awk -F"$DELIM" '{print $5}'` # Extract the first character from the COUNTRY firstChar=`echo ${COUNTRY:0:1}` # Check if it is lowercase if [[ $firstChar == [[:lower:]] ]] then echo "----" echo [ERROR] $LINE # Country cannot begin with a lower case. continue fi # Print valid entries echo "----" echo "SNO: $SNO" echo "COUNTRY: $COUNTRY" echo "CAPITAL: $CAPITAL" echo "CONTINENT: $CONTINENT" echo "CURRENCY: $CURRENCY" done

1. We begin the script by storing the delimiter value comma (,) in the DELIM variable.

3. For each line we count the number of fields and store it in a variable named totalVars.

4. We verify the count of totalVars. If not 5, we simply display the error message and move on to the next record using the continue statement.

6. If totalVars is 5, we extract the information from the line and populate the variables SNO, COUNTRY, CAPITAL, CONTINENT, and CURRENCY respectively.

7. Using parameter expansion, we pull out the first character from the COUNTRY variable.

8. We check if the first character is in lowercase. If it is, our script displays the error message and continues with the next iteration.

10. We display all the valid records.

Best practices when using the continue statement

  • We need to maintain caution when dealing with the continue statements in Bash. This is to avoid making the code difficult to read and understand.

  • Complex nested loops and conditional statements with the continue statement can be fatal as one wrong use of continue will completely skip the iteration.

  • We should be clear in our approach by outlining the conditions clearly before we start using the continue statement. This will enable us to ignore the unwanted iterations.

  • Using comments just before the continue statement will make the script easy to interpret.

2. We start the body of the script by named records.csv one line at a time.

reading the csv file
Bash
showing sample csv record
example bash script for loop with continue process lines in a csv file
output of bash script - for loop with continue
understand continue in bash