您的位置:首页 > 运维架构 > Shell

(12)shell for while until循环

2016-02-03 09:34 661 查看

1、for循环

一般格式为:

for 变量 in 列表
do
command1
command2
...
commandN
done


说明:

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。

每循环一次,就将列表中的下一个值赋给变量。

in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5


for str in 'This is a string'
do
echo $str
done

运行结果:
This is a string

因为for循环列表就是一个单引号引起来的字符串。


#!/bin/bash
for FILE in $HOME/.bash*
do
echo $FILE
done

运行结果:
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc

遍历所以以.bash开头的文件。


2、while循环

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:

while command
do
Statement(s) to be executed if command is true
done


命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。

以下是一个基本的while循环,测试条件是:如果COUNTER小于5,那么返回 true。COUNTER从0开始,每次循环处理时,COUNTER加1。运行上述脚本,返回数字1到5,然后终止。

COUNTER=0
while [ $COUNTER -lt 5 ]
do
COUNTER='expr $COUNTER+1'
echo $COUNTER
done

运行脚本,输出:
1
2
3
4
5


while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量FILM,按<Ctrl-D>结束循环。
echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
while read FILM
do
echo "Yeah! great film the $FILM"
done

运行脚本,输出类似下面:
type <CTRL-D> to terminate
enter your most liked film: Sound of Music
Yeah! great film the Sound of Music


3、until循环

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。

一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。

until 循环格式为:

until command
do
Statement(s) to be executed until command is true
done


command 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。

例如,使用 until 命令输出 0 ~ 9 的数字:

#!/bin/bash
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
运行结果:
0
1
2
3
4
5
6
7
8
9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: