The if Statement

The if statement evaluates a logical expression to make a decision. An if condition has the following format in pdksh and bash:

Statements elif [ expression ]; then Statements else

Statements fi

The if conditions can be nested. That is, an if condition can contain another if condition within it. It isn't necessary for an if condition to have an elif or else part. The else part is executed if none of the expressions that are specified in the if statement and are optional if subsequent elif statements are true. The word fi is used to indicate the end of the if statements, which is very useful if you have nested if conditions. In such a case, you should be able to match fi to if to ensure that all if statements are properly coded.

In the following example for bash or pdksh, a variable var can have either of two values: Yes or No. Any other value is invalid. This can be coded as follows:

if [ $var = "Yes" ]; then echo "Value is Yes" elif [ $var = "No" ]; then echo "Value is No" else echo "Invalid value"

In tcsh, the if statement has two forms. The first form, similar to the one for pdksh and bash, is as follows:

if (expression) then

Statements else if (expression) then Statements else

Statements endif

The if conditions can be nestedthat is, an if condition can contain another if condition within it. It isn't necessary for an if condition to have an else part. The else part is executed if none of the expressions specified in any of the if statements are true. The optional if part of the statement (else if (expression) then) is executed if the condition following it is true and the previous if statement is not true. The word endif is used to indicate the end of the if statements, which is very useful if you have nested if conditions. In such a case, you should be able to match endif to if to ensure that all if statements are properly coded.

Using the example of the variable var having only two values, Yes and No, here is how it would be coded with tcsh:

if ($var == "Yes") then echo "Value is Yes"

else if ($var == "No" ) then echo "Value is No" else echo "Invalid value" endif

The second form of the if condition for tcsh is as follows:

if (expression) command

In this format, only a single command can be executed if the expression evaluates to true.

Was this article helpful?

0 0

Post a comment