一、for循环语句
在linux中,for循环语句的逻辑和使用方法与其他编程语言类似,允许你创建一个遍历一系列值的循环,每次迭代都使用其中一个值来执行已定义好的一组命令。
for var in list
do
commands
done
for命令用空格来划分list中的每个值。如果在单独的数据值中有空格,就必须用双引号将这些值圈起来。
#!/bin/bash
# an example of how to properly define values
for test in Nevada "New Hampshire" "New Mexico" "New York"
do
echo "Now going to $test"
done
你也可以更改环境变量IFS(内部字段分隔符),重新规定分隔符:
$ cat states
Alabama
Alaska
Arizona
Arkansas
Colorado
Connecticut
Delaware
Florida
Georgia
#!/bin/bash
# reading values from a file
file="states"
IFS=$'\n'
for state in $(cat $file)
do
echo "Visit beautiful $state"
done
你也可以像C语言那样写计数器迭代:
$ cat test8
#!/bin/bash
# testing the C-style for loop
for (( i=1; i <= 10; i++ ))
do
echo "The next number is $i"
done
$ ./test8
The next number is 1
The next number is 2
The next number is 3
The next number is 4
The next number is 5
The next number is 6
The next number is 7
The next number is 8
The next number is 9
The next number is 10
二、while循环语句
在linux中,while命令的格式是:
while test command
do
other commands
done
while命令的关键在于所指定的test command的退出状态码必须随着循环中运行的命令而改变。如果退出状态码不发生变化, while循环就将一直不停地进行下去。
最常见的test command的用法是用方括号来检查循环命令中用到的shell变量的值。
#!/bin/bash
# while command test
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
$ ./test10
10
9
8
7
6
5
4
3
2
1
$
参考资料:《linux命令行与shell脚本编程大全.第三版》
Linux中for和while循环语句介绍

被折叠的 条评论
为什么被折叠?



