Using loop with a continue in Linux bash script

Using the continue command, it is possible to exit from the current iteration of the loop and resume the next iteration of the loop. We use the for, while, or until commands for loop iterations.

The following is the for_09.sh script for the loop with the continue command to skip a certain part of the loop commands:

for_09.sh

#!/bin/bash 
for x in 1 2 3 
do 
    echo before $x 
    continue 1 
    echo after $x 
done 
exit 0 

Let’s test the program:

$ chmod +x for_09.sh
$ ./for_09.sh

The following will be the output after executing the preceding commands:

Output:

before 1before 2before 3

The following is the for_10.sh script in which we will check all files and directories. If the file is found, we will print the name. If the directory is found, we will skip further processing with the continue command. Take care that any of your useful files with the name sample* are not in the testing directory before testing this script:

for_10.sh

#!/bin/bash 
rm -rf sample* 
echo > sample_1 
echo > sample_2 
mkdir sample_3 
echo > sample_4 
 
for file in sample* 
do 
  if [ -d "$file" ] 
  then 
    echo "skipping directory $file" 
    continue 
  fi 
  echo file is $file 
done 
rm -rf sample* 
exit 0 

Let’s test the program:

$ chmod +x for_10.sh
$ ./for_10.sh

The following will be the output after executing the preceding commands:

Output:

file is sample_1file is sample_2skipping directory sample_3file is sample_4

In the following  for_11.sh script, we are checking the backup of files in the /MP3/ folder. If the file is not found in the folder, we are copying it to the folder for backup purposes. We can implement incremental backup scripts using this functionality:

for_11.sh

#!/bin/bash 
for   FILE in 'ls *.mp3' 
do 
  if  test -e /MP3/$FILE 
  then 
    echo "The file $FILE exists." 
    continue 
  fi 
  cp $FILE /MP3 
done 

Let’s test the program:

$ chmod +x for_11.sh
$ ./for_11.sh

If the file exists in the MP3 folder, then the loop will continue to check the next file. If the file backup is not present in the MP3 folder, then the file will be copied to it.

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

eight − four =