首页 > 系统服务 > 详细

bash shell相关命令记录(6)---for循环、while循环、until循环

时间:2020-03-25 16:13:53      阅读:39      评论:0      收藏:0      [点我收藏+]

1、for循环

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

 

顺序输出字符串

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

输出结果

This is a string


显示 家目录下的sh文件:

for file in /home/tonglei/*.sh
do
    echo $file
done
输出结果

/home/tonglei/case.sh
/home/tonglei/echo.sh
/home/tonglei/for.sh
/home/tonglei/guanxi.sh
/home/tonglei/iffi.sh
/home/tonglei/person.sh
/home/tonglei/shuzu.sh
/home/tonglei/suanshu.sh
/home/tonglei/test.sh
/home/tonglei/tihuan.sh
/home/tonglei/zhuanyi.sh
/home/tonglei/zifucuan.sh

 

2、while 循环

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

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

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

举例

he=0
while [ $he -lt 5 ]
do
        he=`expr $he + 1`  --->注意是反引号
        echo $he
done

执行结果为

1
2
3
4
5

while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量NAME,按<Ctrl-D>结束循环。

echo type ctrl and D to stop
echo -n "enter you name:"
while read name
do
    echo "hello,$name"
done

 3、until循环

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。

until 循环格式为:

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

举例输出0-9

#!/bin/bash
a=0
until [ $a -gt 9 ]
do 
    echo $a
    a=`expr $a + 1`
done

参考自http://c.biancheng.net/cpp/view/7008.html

 

bash shell相关命令记录(6)---for循环、while循环、until循环

原文:https://www.cnblogs.com/chxmtl/p/12566133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!