shell 流程控制


分支语句

  • if else-if else
#! /bin/bash

a=10
b=20
if [ $a == $b ]  #此处用[[]]也是可以的,shell标准手册中推荐使用 [[]]
then
   echo "a 等于 b"
elif [ $a -gt $b ]
then
   echo "a 大于 b"
elif [ $a -lt $b ]
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi
  • case
#! /bin/bash

a=4

case $a in 
    1) echo 'a is 1'
        ;;
    2) echo 'a is 2'
        ;;
    3|4) echo 'a is 3 or 4'
        ;;
    *) echo 'a is others'
        ;;
esac

循环语句

  • for 循环

  shell for 循环

  • while 循环
#! /bin/bash

i=1
while [ $i -le 5 ] 
do
    echo $i
    let "i++"
done
  • until 循环
#! /bin/bash

a=0

until [ ! $a -lt 10 ]
do
    echo $a
    a=`expr $a + 1`
done

跳出循环

  • break
  • continue

总结

  • case 语句中的 ;; 是不能省略的,不会出现C代码中的,不加break,跳到下一个case中继续执行的写法
  • break、continue 只会用于跳出循环

拓展

  • Conditional expressions are used by the [[ compound command and the test and [ builtin commands.
  • The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the (( compound command, the let builtin, or the -i option to the declare builtin
    $ cat demo.sh 
    #! /bin/bash
    int=1
    while (( $int <= 5))     #for ((;;)) 循环也可以这么写
    do
        echo $int
        let "int++"
    done
    
    rivsidn@rivsidn:~/demo/bash/test$ ./demo.sh 
    1
    2
    3
    4
    5

优质内容筛选与推荐>>
1、knockoutjs visible
2、IPV6与子网掩码
3、spring boot 读取配置文件(application.yml)中的属性值
4、安装MySQL的时候遇到的错误
5、windows程序设计之鼠标,键盘,绘制文本简介


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn