[Next] [Previous] [Up] [Top] [Contents]

9.9.1 Conditional if

9.9.1.1 Sh

if condition1

then

command list if condition1 is true

[elif condition2

then command list if condition2 is true]

[else

command list if condition1 is false]

fi

The conditions to be tested for are usually done with the test, or [] command (see Section 8.9.6). The if and then must be separated, either with a <newline> or a semicolon (;).

#!/bin/sh

if [ $# -ge 2 ]

then

echo $2

elif [ $# -eq 1 ]; then

echo $1

else

echo No input

fi

There are required spaces in the format of the conditional test, one after [ and one before ]. This script should respond differently depending upon whether there are zero, one or more arguments on the command line. First with no arguments:

$ ./if.sh

No input

Now with one argument:

$ ./if.sh one

one

And now with two arguments:

$ ./if.sh one two

two


Introduction to Unix - 14 AUG 1996
[Next] [Previous] [Up] [Top] [Contents]