Книга: Fedora™ Unleashed, 2008 edition
The if Statement
The if
Statement
The if
statement evaluates a logical expression to make a decision. An if
condition has the following format in bash
:
if [ expression ]; then
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 in subsequent elif
statements are true. The word fi
is used to indicate the end of an if statement, 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
, 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"
fi
- 10.2 Modifying the .emacs File Directly
- Conditional Statements
- Special Statements: for, while, and Others
- The for Statement
- The while Statement
- The until Statement
- The shift Statement
- The case Statement
- The break and exit Statements
- Handling Exceptions Using the try-catch Statement
- Throwing Exceptions Using the throw Statement
- The finally Statement