Bash Continue – Using with for Loop
Last updated
Last updated
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
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.
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
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.
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.
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.
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:
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.
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.