shell单分支if语句

一 单分支if条件语句
if [ 条件判断式];then
程序
fi
或者
if [ 条件判断式]
then
程序
fi
 
二 语法解析
1、if语句使用fi结尾,和一般语言使用大括号结尾不同。
2、[条件判断式]就是使用test命令判断,所以中括号和条件判断式之间必须有空格。
3、then后面跟符合条件之后执行的程序,可以放在[]之后,用“;”分割。也可以换行写入,就不需要用“;”了。
 
三 实例
#!/bin/bash
test=$(env | grep USER |cut -d "=" -f 2)
if [ "$test" == "root" ]
then
echo "you are root"
fi
 
四 运行结果
you are root
 
五 判断分区使用率
#!/bin/bash
rate=$(df -h|grep "/dev/sda3"|awk '{print $5}'|cut -d "%" -f1)
if [ $rate -le 80 ]
then
echo "/dev/sda3 is not full"
fi
 
六 运行结果
/dev/sda3 is not full

猜你喜欢

转载自cakin24.iteye.com/blog/2393040