Книга: 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

Оглавление книги


Генерация: 0.580. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз