Name

if - Conditional command execution

Syntax

if expression then [ command1 [ else command2 ] ]

Description

If tests the expression, and if it results in a true value, performs command1 following the then keyword. If the expression is false, and an else keyword is given, command2 is performed.

Multiple Lines


If statements can span more than one line in order to issue multiple commands. This is an example of a compound if statement:

if expression then command command ... endif

The endif keyword denotes the end of a compound if statement. Here’s an example using an else option:

if expression then command1 ... else command2 ... endif

Expressions


Typical expressions include:

x = y

Equality (== can be used)

x <> y

Inequality (!= can be used)

x > y

Greater

x < y

Smaller

x >= y

Greater or equal

x <= y

Less or equal

-f file

Existence of a file

The values for x and y in expressions can be any kind of argument, including variables. Multiple expressions can be included as well, with parenthesis used for precedence. To mix expressions logically, separate them with these two keywords or symbols: and (&&), or (||). To negate the result of an expression, precede it with the keyword not (also !). Example:

if $a = $b then echo TRUE else echo FALSE

Another example:

if $time[0] = "Sun" and -f workfile then echo It is Sunday AND the workfile exists! else echo EITHER it is not Sunday echo OR the workfile does not exist. endif

Nested Statements


Nested if statements can be used in a script, as shown:

if ( expr1 ) then if ( expr2 ) then echo "expr1 AND expr2 are true" endif else echo "Either expr1 OR expr2 is false" endif

Each if must have a matching endif.

See Also

csh(C), scripts(M)