Unix 简明教程
Unix / Linux - Shell Decision Making
在本章中,我们将了解 Unix 中的 shell 决策制定。在编写 shell 脚本时,可能会遇到需要在给定的两条路径中选择一条路径的情况。因此,您需要使用条件语句,让您的程序可以做出正确的决策并执行正确操作。
In this chapter, we will understand shell decision-making in Unix. While writing a shell script, there may be a situation when you need to adopt one path out of the given two paths. So you need to make use of conditional statements that allow your program to make correct decisions and perform the right actions.
Unix Shell 支持条件语句,用于根据不同的条件执行不同的操作。现在,我们将了解此处的两个决策制定语句 −
Unix Shell supports conditional statements which are used to perform different actions based on different conditions. We will now understand two decision-making statements here −
-
The if…else statement
-
The case…esac statement
The if…else statements
if else 语句是有用的决策制定语句,可用于从给定的一组选项中选择一个选项。
If else statements are useful decision-making statements which can be used to select an option from a given set of options.
Unix Shell 支持以下 if…else 语句形式 −
Unix Shell supports following forms of if…else statement −
大多数 if 语句使用上一章中讨论的关系运算符来检查关系。
Most of the if statements check relations using relational operators discussed in the previous chapter.
The case…esac Statement
您可以使用多个 if…elif 语句执行多路分支。但是,这并不总是一种最佳解决方案,尤其是当所有分支都依赖于单个变量的值时。
You can use multiple if…elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Unix Shell 支持 case…esac 语句,该语句可以精确地处理这种情况,而且比重复的 if…elif 语句更高效。
Unix Shell supports case…esac statement which handles exactly this situation, and it does so more efficiently than repeated if…elif statements.
只有一种形式的 case…esac 语句,此处已对其进行了详细描述 −
There is only one form of case…esac statement which has been described in detail here −
Unix shell 中的 case…esac 语句与我们在其他编程语言中有的 switch…case 语句非常类似,例如 C 或 C++ 和 PERL 等。
The case…esac statement in the Unix shell is very similar to the switch…case statement we have in other programming languages like C or C++ and PERL, etc.