Unix 简明教程
Unix / Linux - Shell Loop Types
在本章节中,我们将讨论 Unix 中的 shell 循环。循环是一个功能强大的编程工具,使您能够重复执行一组命令。在本章中,我们将检查 shell 编程人员可用的以下类型的循环−
In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −
根据具体情况,您将使用不同的循环。例如, while 循环会在给定条件保持真时执行给定的命令; until 循环会在给定条件变为真时执行。
You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true.
一旦您有了良好的编程习惯,您将获得专业知识,因此,开始根据具体情况使用适当的循环。此处, while 和 for 循环在大多数其他编程语言中可用,如 C 、 C++ 和 PERL 等。
Once you have good programming practice you will gain the expertise and thereby, start using appropriate loop based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++ and PERL, etc.
Nesting Loops
所有循环都支持嵌套概念,这意味着您可以将一个循环放入另一个类似循环或不同循环中。根据您的要求,这种嵌套可以进行无限次。
All the loops support nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to unlimited number of times based on your requirement.
以下是一个嵌套 while 循环的示例。其他循环可以类似地根据编程要求进行嵌套−
Here is an example of nesting while loop. The other loops can be nested based on the programming requirement in a similar way −
Nesting while Loops
可以将一个 while 循环用作另一个 while 循环的主体的一部分。
It is possible to use a while loop as part of the body of another while loop.
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true
while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done
Statement(s) to be executed if command1 is true
done
Example
这里有一个简单的循环嵌套示例。让我们在您用来计数到九的循环中添加另一个倒数循环−
Here is a simple example of loop nesting. Let’s add another countdown loop inside the loop that you used to count to nine −
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
这将产生以下结果。重要的是要注意 echo -n 在此处如何工作的。此处 -n 选项让 echo 避免打印一个新行字符。
This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0