If-Then-Else



next up previous contents index
Next: Case Up: Shell Programs (Scripts) Previous: Loop through Arguments:

If-Then-Else

Shell scripts may contain simple if-then-else structures like Fortran or C:


if [ test ] then command else Else is optional. command fi if always finishes with fi.

The test may deal with file characteristics or numerical/string comparisons. Although the left bracket here appears to be part of the structure, it is actually another name for the Unix test command (located in /bin/[). Since [ is the name of a file, there must be spaces before and after it as well as before the closing bracket. To use the Korn shell's built-in test command, replace the single pair of square brackets with [[ ]] a pair of double brackets. 


TEST OPTIONS, FILE TESTS
-sfile
Test if file exists and is not empty.
-ffile
Test if file is an ordinary file, not a directory.
-dfile
Test if file is a directory.
-wfile
Test if file has write permission.
-rfile
Test if file has read permission.
-xfile
Test if file is executable.
!
Not operation for test.


TEST OPTIONS, STRING COMPARISONS
$X -eq $Y
Test if $X is equal to $Y.
$X -ne $Y
Test if $X is not equal to $Y.
$X -gt $Y
Test if $X is greater than $Y.
$X -lt $Y
Test if $X is less than $Y.
$X -ge $Y
Test if $X is greater than or equal to $Y.
$X -le $Y
Test if $X is less than or equal to $Y.
"$A" = "$B"
Test if string $A is equal to string $B.

TEST OPTIONS, NOT (!)
"$A" != "$B"
Test if string $A is not equal to string $B.
$X ! -gt $Y
Test if $X is not greater than $Y.

The next example is a script that takes one argument, a file name. If the file exists, it is used as the input for the user's program. If the number of arguments is incorrect or if the input file does not exist, the script prints out a message and exits:


#!/bin/sh if [ $# -ne 1 ] then echo "This script needs one argument." exit -1 fi input="$1" if [ ! -f "$input" ] then echo "Input file does not exist." exit -1 else echo "Running program bigmat with input $input." bigmat < $input fi exit



next up previous contents index
Next: Case Up: Shell Programs (Scripts) Previous: Loop through Arguments: