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


    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

  • 相关阅读:
    一个完整的移动端项目的构建步骤——框架搭构1
    简单日历,纯js
    javascript语句语义大全(7)
    微软笔试Highway问题解析
    中国电信翼支付2014编程大赛决赛
    海岛问题
    大数计算
    Dijkstra算法
    Android测试之Keycode
    字符串解析
  • 原文地址:https://www.cnblogs.com/chxmtl/p/12566133.html
Copyright © 2020-2023  润新知