Linux 下的 shell 编程之 if-else选择结构

来源:互联网 发布:python 项目打包部署 编辑:程序博客网 时间:2024/06/06 09:50

 Linux 中 shell 中if else 的使用方式比较简单,. 相关的关键字有: if, elif , else, fi, 等.

  1. if 的判断表达式是 []

  2. if 的范围确定不是依靠 {} ,而是if  fi


一 if-else 常用结构

    1. if - else 结构

# 第一种写法: 需要写, 要注意缩进if [ 条件判断表达式 ] ; then    程序块儿else     程序块儿fi# 第二中写法: 不需要写, 要注意缩进if [ 条件判断表达式 ] then   程序块儿else    程序块儿fi


    2. if - elif - else 结构:

# 第一种写法: 需要写, 要注意缩进if [ 条件判断表达式 ] ; then    程序块儿elif [ 条件表达式 ] ; then    程序块儿else     程序块儿fi# 第二中写法: 不需要写, 要注意缩进if [ 条件判断表达式 ] then   程序块儿elif [ 条件表达式 ]   then   程序块儿else    程序块儿fi

二  if 常用举例

    1. 判断分区占用率是否超过80%

    

#!/bin/bash#Desc统计跟分区使用率#Authzonggf#Date2016-07-02 10:39:13#获取分区使用率rate=$(df -h | grep "/dev/sda5" | awk '{print $5}' | cut -d "%" -f1)#如果分区使用率超过80%,提示警告信息if [ $rate -gt 80 ]   then    echo Warning! The boot is nearly full! It is already $rate% !      else    echo The boot area is safe! It is $rate%fi

    2. 测试if -elif -else

#!/bin/bash#Descfor test if-else-if#Authzonggf#Date2016-07-02 11:21:01read -p "请输入一个数字:" numif [ $num -eq 20 ] ; then  echo "$num > 20"elif [ $num -eq 100 ] ; then  echo "$num > 100"else  echo "$num < 20"fi


1 0