Exiting from the current loop iteration with the continue command

With the help of the continue command, it is possible to exit from the current iteration of the loop and to 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:

#!/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:

before 1
before 2
before 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:

#!/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:

file is sample_1
file is sample_2
skipping directory sample_3
file is sample_4

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

#!/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.

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

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