Shell Conditionals

In addition to the built-ins listed in Tables 3.6 and 3.7, the Bourne shell also contains some simple conditionals. A conditional command makes a choice depending on the outcome of a condition. Examples of simple conditionals are && and ||, which I will discuss along with the if and case conditionals in this section.

&& and ||

The simplest conditional in the Bourne shell is the double ampersand (&&). When two commands are separated by a double ampersand, the second command executes only if the first command returns a zero exit status (an indication of successful completion). The following is an example:

ls -ld /usr/bin > /dev/null && echo "Directory Found" 

If the directory /usr/bin exists, the message Directory Found is displayed.

The opposite of && is the double bar (||). When two commands are separated by ||, the second command executes only if the first command returns a nonzero exit status (indicating failure). The following is an example:

ls –d  /usr/foo || echo "No directory found" 

If the directory does not exist, the following message is displayed:

/usr/foo: No such file or directory 
No directory found 

true and false Programs

The Bourne shell contains the special programs true and false. The only function of the true program is to return a true (zero) exit status. Similarly, the function of the false program is to return a false (nonzero) exit status. The following is an example:

true && echo True 

The system responds with True. The following is another example:

false || echo False 

The system responds with False. True and false tests will be discussed later when we discuss the if and while conditionals.

Note

&& and || are useful conditionals for creating simple scripts, but additional functionality is sometimes required. Therefore, the Bourne shell offers the if and case conditionals.


if

One of the more important built-ins of the Bourne shell is the if conditional. The syntax of the if conditional is as follows:

if condition-list 
       then list 
      elif condition-list 
       then list 
    else list 
fi 

The list following if is executed. If it returns a zero exit status, the list following the first then is executed. Otherwise, the list following elif is executed. If its value is zero, the list following the next then is executed. Failing that, the else list is executed. If no list is executed, the if command returns a zero exit status.

The next example illustrates the use of an if conditional statement:

if  [ -f  /tmp/errlog ] 
    then 
        rm /tmp/errlog 
        echo "Error log has been removed" 
    else 
        echo "No errorlog  has been found" 
fi 

In this example, the program checks for a file named /tmp/errlog. If the file is present and is a regular file, the program removes it. If the file is not present, the file prints a message.

The Test Program

The previous example used the if test [ -f /tmp/errlog ] to evaluate a conditional expression. At the heart of each control structure is a conditional test. The test command is commonly used in shell programs to perform various tests and to determine whether certain files and directories exist. The test program performs three types of tests:

  • It can test files for certain characteristics, such as file type and permissions.

  • It can perform string comparisons.

  • It can make numeric comparisons.

test indicates the success or failure of its testing by its exit status. test evaluates an expression and, if its value is true, sets a zero (true) exit status. Otherwise, a nonzero (false) exit status is set. All shell commands return a true (0) value when they complete successfully or a false (1) value when they fail. You can display the exit status of the last shell command by looking at the $? variable with the echo command. Table 3.8 lists some of the common conditions that can be evaluated.

Table 3.8. Built-In Test Functions
Test Condition Description
r <filename> True if the filename exists and is readable.
w <filename> True if the filename exists and is writeable.
x <filename> True if the filename exists and is executable.
f <filename> True if the filename exists and is a regular file.
d <filename> True if the filename exists and is a directory.
h <filename> True if the filename exists and is a symbolic link. With all other primitives (except -L filename), the symbolic links are followed by default.
c <filename> True if the filename exists and is a character special file.
b <filename> True if the filename exists and is a block special file.
u <filename> True if the filename exists and its set-user-ID bit is set.
g <filename> True if the filename exists and its set-group-ID bit is set.
k <filename> True if the filename exists and its sticky bit is set.
n <filename> True if the length of the string is nonzero.
s <filename> True if the filename exists and has a size greater than zero.
z <filename> True if the length of the string is zero.
<s1> = <s2> True if strings s1 and s2 are identical.
<s1> != <s2> True if strings s1 and s2 are not identical.
<n1> -eq <n2> True if the integers n1 and n2 are algebraically equal. Any of the comparisons -ne, -gt, -ge, -lt, and -le can be used in place of -eq.
L <filename> True if the filename exists and is a symbolic link. With all other primitives (except -h <filename>), the symbolic links are followed by default.
These Test Functions Can Be Combined with the Following Operators:
! Unary negation operator.
a Binary and operator.
o Binary or operator (-a has higher precedence than -o).
(expression) Parentheses for grouping. Notice also that parentheses are meaningful to the shell and, therefore, must be quoted.

The following is an example of where you might use a unary operator:

if  [ ! -f  /tmp/errlog ] 
    then 
        echo "No error log has been found" 
fi 

In this example, the statement [ ! -f /tmp/errlog ] tests whether the file /tmp/errlog does not exist.

case

Many programs are menu driven, meaning they offer the user a menu of choices from which to select. The case statement makes it easy to set up a menu of choices. The general syntax for a case statement is as follows:

case value in 
choice1) commands;; 
choice2) commands;; 
... 
esac 

A case command executes the list associated with the first pattern that matches the choice. The following is an example to describe how a case statement works:

echo Please enter the letter next to the command that you want to select: 
echo 'a  date' 
echo 'b  ls' 
echo 'c  who' 
read choice 
case $choice in 
a) date;; 
b) ls;; 
c) who;; 
*)   echo Invalid choice - Bye. 
esac 

The list of choices is scanned to find the one that matches the value input by the user. The choice *) matches any value, so it’s usually added as a last option—a catchall.

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

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