美文网首页
08. Shell脚本逻辑判断

08. Shell脚本逻辑判断

作者: Lv_0 | 来源:发表于2018-03-21 19:51 被阅读0次
    • if 判断

    1. if开始判断,反顺序fi结束
    2. if后跟判断条件,then后跟条件成立后,要执行的代码
    3. if不满足的时候,则执行else
    4. elif为当上一个条件不满足时才会执行
    5. 判断条件必须以 (()) 包括,不得缺少
    6. 判断条件也可以使用 [] ,但[]和条件之间必须有空格,且条件的判断不可再使用 < 这些符号,需使用 -lt
    符号 代表符 含义
    = -eq 等号
    != -ne 不等于
    > -gt 大于
    >= -ge 大于等于
    < -lt 小于
    <= -le 小于等于
    1. shell脚本中if还常判断文件的属性,使用[ -xxx filename ]
    参数 含义
    -e 判断文件或目录是否存在
    -d 判断是否是目录,且此目录是否存在
    -f 判断是否是普通文件,且此文件是否存在
    -r 判断是否有读权限
    -w 判断是否有写权限
    -x 判断是否有执行权限
    1. shell语句中,一行若要写多条语句,则必须以 ; 分号分割.若换行,则无需 ; 分号结尾
    #! /bin/bash
    
    #Init var
    score="Pls input your score :"
    exam_not="Sorry ! You didn't pass the exam."
    exam_yes="Congratulation ! You pass the exam."
    
    # If
    read -p "$score" a
    if ((a<60));then
            echo $exam_not
    fi
    
    # If & else
    read -p "$score" b
    if ((b<60));then
            echo $exam_not
    else
            echo $exam_yes
    fi
    
    # If & else & elif
    read -p "$score" c
    if ((c<60))
    then
            echo $exam_not
    elif ((c>=60 && c<=100));then
            echo $exam_yes
    else
            echo "Sorry ! The information of you had inputted is wrong !"
    fi
    
    # []
    d=10;if [ $d -gt 5 ];then echo "Pass !";fi
    
    # File attr
    if [ -r test01_if.sh ];then echo "Has !";fi
    
    image.png

    • case 分支

    1. case可以有无限个分支
    2. case语句必须以反数序单词esac结束
    3. 选项*代表前面的选项不满足时执行的分支
    4. 每个分支必须以;;结束
    #! /bin/bash
    # Judge the number is even or odd !
    
    read -p "Pls input a num : " a
    b=$[$a%2]
    case $b in
    1)
            echo "The num is even !"
            ;;
    0)
            echo "The num is odd !"
            ;;
    *)
            echo "It is error !"
            ;;
    esac
    
    image.png

    相关文章

      网友评论

          本文标题:08. Shell脚本逻辑判断

          本文链接:https://www.haomeiwen.com/subject/goymqftx.html