流程控制 -if语句
1.单分支if条件语句
语法:
if [ 条件判断式 ];then
程序
fi
或者
if [ 条件判断式 ]
then
程序
fi
注意: 1) if语句使用fi结尾,和一般语言大括号结尾不同
2) [ 条件判断式 ] 就是利用test命令判断,所以中括号和条件判断式之间必须 有空格
3)then 后面跟符合条件之后执行的程序,可以放在[]之后,用“;“分割。也可以换行写入,就不需要”:“了。
例:统计分区使用率
#!/bin/bash
rate=$(df -h | grep /dev/sda3 | awk '{ print $5} ' | cut -d "%" -f1)
if [ $rate -ge 10 ]
then
echo "Waring!/dev/sda3 is full!!!!"
fi
运行结果:
2.双分支if条件语句
语法:
if [ 条件判断 式 】
then
条件成立时,执行的程序
else
条件不成立时,执行的另一个程序
fi
例 :备份mysql数据 库
#!/bin/bash
date=$(date +%y%m%d)
size=$(du -sh /etc)
if [ -d /tmp/dbback ]
then
echo "Data is : $date" > /tmp/dbback/db.txt
echo "size is : $size" >> /tmp/dbback/db.txt
tar -zcf etc_$date_$size.tar.gz /etc db.txt &>/dev/null
rm -rf /tmp/dbback/db.txt
else
mkdir /tmp/dbback
echo "Data is : $date" > /tmp/dbback/db.txt
echo "size is : $size" >> /tmp/dbback/db.txt
tar -zcf etc_$date_$size.tar.gz /etc db.txt &>/dev/null
rm -rf /tmp/dbback/db.txt
fi
3.多分支if条件语句
if [ 条件判断式1 】
then
当条件成立时,执行程序 1
elseif 【 条件判断式2 }
当条件判断2成立时,执行程序2
........
fi
例:判断用户输入是什么文件
#!/bin/bash
read -p "Please input a filename:" file
if [ -z "$file" ]
then
echo "Error,please input a filename"
exit 1
elif [ ! -e "$file" ]
then
echo "your inut is not a file"
exit 2
elif [ -f "$file" ]
then
echo "$file is a regulare file!"
elif [ -d "$file" ]
then
echo "$file is a directory!"
else
echo "$file is an other file"
fi
运行结果: