(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
相关文章推荐
- (11)shell case esac语句
- (10)shell 判断表达式
- shell 编程8 获取 java程序的pid 杀死pid 对应的进程
- (9)shell printf命令:格式化输出
- (8)shell echo命令
- (7)shell数组
- (6)shell字符串
- (5)shell运算符
- 安装XShell 5出现msvcp110.dll错误
- Linux下Java程序的启动shell脚本
- Linux下Java程序的启动shell脚本
- linux shell常用语法
- shell 练习题集合(思路和解答)
- (4)shell替换
- (3)shell特殊变量
- ssh远程执行shell实例
- (2)第一个shell脚本和shell变量
- shell之路【第一篇】shell简介与入门
- Linux中profile、bashrc、bash_profile之间的区别和联系
- grep 仅显示匹配部分