Using thecontinuecommand, it is possible to exit fromthecurrent iteration of theloopand resume the next iteration of the loop. We use thefor,while, oruntilcommands for loop iterations.
The following is thefor_09.shscript for the loop with thecontinuecommand 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.
