Controlling the loop

Having entered our loop, we may need to either exit the loop prematurely or perhaps exclude certain items from processing. If we want to process only directories in a listing, rather than every file of any type, then to implement this, we have loop control keywords, such as break and continue.

The break keyword is used to exit the loop, processing no more entries, whereas the continue keyword is used to stop the processing of the current entry in the loop and resume the processing with the next entry.

Assuming we only want to process directories, we could implement a test within the loop and determine the file type:

$ for f in * ; do
[ -d "$f" ] || continue
chmod 3777 "$f"
done

Within the loop, we want to set permissions, including the SGID and sticky bits, but for the directories only. The * search will return all files; the first statement within the loop will ensure that we only process directories. If the test is done for the current loop, the target fails the test and is not a directory; the continue keyword retrieves the next loop-list item. If the test returns true and we are working with a directory, then we will process the subsequent statements and execute the chmod command.

If we need to run the loop until we find a directory and then exit the loop, we can adjust the code so that we can iterate though each file. If the file is a directory, then we exit the loop with the break keyword:

$ for f in * ; do
[ -d "$f" ] && break
done
echo "We have found a directory $f"  

Within the following screenshot, we can see the code in action:

By working with the same theme, we can print each directory found in the listing using the following code:

for f in * ; do
[ -d "$f" ] || continue
dir_name="$dir_name $f"
done
echo "$dir_name"  

We can achieve a result by processing the loop item only if it is a directory and within the loop. We can work with regular files only using the if test. In this example, we append the directory name to the dir_name variable. Once we exit the loop, we print the complete list of directories. We can see this in the following screenshot:

Using these examples and your own ideas, you should now be able to see how you can control loops using the continue and break keywords.

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

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