18.2. Control structures

With very few exceptions, nearly all scripts have some type of flow control in them. What is flow control? Well, suppose you had a script containing a few commands like this:


#!/bin/sh 
# make a directory 
mkdir /home/dave/mydocs 
# copy all doc files 
cp *.docs /home/dave/docs 
# delete all doc files 
rm *.docs 

The above is a script; it does a job – what’s the problem? The problem is what happens if the directory cannot be created. What happens if the directory can be created but fails when the copy tries to copy the files? What if you need to cp different files from different directories. We need to make informed decisions before the command takes place or more likely on the outcome of the last command. The shell comes to our rescue here in providing a series of command statements that can help you take appropriate action when a command succeeds or fails, or if you need to process a list. These command statements fall into two categories:


Iteration 

and


Flow control 

18.2.1. Flow control

if, then, else statements provide conditional tests. The test can be based on a variety of things, like the size or permissions of a file, or comparing values or strings. These tests return either a true (0) or a false (1) value, and based on this result you then take further action. We have seen some of these tests already when we dealt with conditional testing.

case statements let you match up patterns, words or values. Once this pattern or value is matched, you can then do other statements based purely on this matched condition.

18.2.2. Iteration

Iteration or looping is the process of executing repeatedly a series of commands. There are three looping statements at our disposal:

for loop Will process all information once in a list until that information is exhausted.
until loop The least used of the looping statements, the until loop will loop continuously waiting for a condition to be true. The test part is at the end of the loop.
while loop The while loop will loop until a certain condition is met. The test part is at the top of the loop.

Any of the iteration of flow control statements can be nested. For example you can have a for loop within a for loop.

Now we know a bit about iteration and control flow let’s do some scripts.

From now on all the echo statements in the scripts will use the LINUX or BSD version. That is to say we will use this method of echo ‘ echo -e -n ’, which keeps the new line at the end of the echo from being executed. To implement a universal echo command that works on both types of UNIX (System V and BSD), see Chapter 19 on shell functions.

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

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