The continue keyword

As with most things in Bash (and life), there is a Yang to the Yin that is break: the continue  keyword. If you use continue, you're telling the loop to stop the current loop, but continue with the next run. So, instead of stopping the entire loop, you'll just stop the current iteration. Let's see if another example can make this clear:

reader@ubuntu:~/scripts/chapter_11$ vim for-continue.sh
reader@ubuntu:~/scripts/chapter_11$ cat for-continue.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-10-28
# Description: For syntax with a continue.
# Usage: ./for-continue.sh
#####################################

# Look at numbers 1-20, in steps of 2.
for number in {1..20..2}; do
if [[ $((${number}%5)) -eq 0 ]]; then
continue # Unlucky number, skip this!
fi

# Show the user which number we've processed.
echo "Looking at number: ${number}."

done

In this example, all of the numbers that can be divided cleanly by 5 are considered unlucky and should not be processed. This is achieved by the [[ $((${number}%5)) -eq 0 ]] condition:

  • [[ $((${number}%5)) -eq 0 ]] -> test syntax
  • [[ $((${number}%5)) -eq 0 ]] -> arithmetic syntax
  • [[ $((${number}%5)) -eq 0 ]] -> modulo 5 of the variable number

If the number passes this test (and is thus cleanly divisible by 5, such as 5, 10, 15, 20, and so on), continue is executed. When this happens, the next iteration of the loop is run (and echo is NOT executed!), as can be seen when running this script:

reader@ubuntu:~/scripts/chapter_11$ bash for-continue.sh 
Looking at number: 1.
Looking at number: 3.
Looking at number: 7.
Looking at number: 9.
Looking at number: 11.
Looking at number: 13.
Looking at number: 17.
Looking at number: 19.

As the list should imply, the numbers 5, 10, and 15 are processed, but we do not see them in echo. We can also see everything after, which would not have happened with break. Verify if this is actually happening with bash -x (warning: loads of output!) and check what happens if you replace continue with break or even exit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.17.64