1. 单分支if条件语句
单分支if条件语句有三种写法:
if [ 条件判断式 ]; then
程序
fi
或者
if [ 条件判断式 ]
then
程序
fi
或者
if [ 条件判断式 ];then 操作;fi
说明:只有条件成立,才执行相应的操作。
示例:
if [ aa==aa ];then echo yes;fi
注意要点:
- if语句使用fi结尾。
- [ 条件 ] 中括号的内部两侧必须有空格。
- 如果then和上面的if判断在同一行,要用分号;分割。
示例:判断根分区的使用率
写一个shell脚本usage.sh:
#!/bin/bash# 判断根分区的使用率
# Author: root
rate=$(df -h | grep "/dev/sda3" | awk '{print $5}' | cut -d "%" -f1)
# 把根分区/dev/sda3的使用率作为值赋予变量rate
if [ $rate -ge 80 ];then
echo "Warning! /dev/sda3 is full"
fi
2. 双分支if条件语句
基本格式:
if [ 条件 ]
then
条件成立时,执行操作1
else
条件不成立时,执行操作2
fi
示例:备份mysql数据库
#!/bin/bash
#备份mysql数据库
#Author: root
ntpdate asia.pool.ntp.org &>/dev/null
#同步系统时间,并将执行结果直接丢弃(即不输出到屏幕)
#Linux默认没有ntpdate命令,可用 yum -y install ntpdate 安装
date=$(date +%y%m%d)
#把当前系统时间按照“年月日”格式赋予变量date
size=$(du -sh /var/lib/mysql)
#统计mysql数据库的大小,并把其赋予size变量
if [ -d /tmp/dbbak ]
then
echo "Date: $date" > /tmp/dbbak/dbinfo.txt
echo "Data size: $size" >> /tmp/dbbak/dbinfo.txt
cd /tmp/dbbak
tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null
rm -rf /tmp/dbbak/dbinfo.txt
else
mkdir /tmp/dbbak
echo "Date: $date" > /tmp/dbbak/dbinfo.txt
echo "Data size: $size" >> /tmp/dbbak/dbinfo.txt
cd /tmp/dbbak
tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null
rm -rf /tmp/dbbak/dbinfo.txtfi
3. 多分支if条件语句
基本格式:
if [ 条件1 ]
then
当条件1成立时,执行操作1
elif [ 条件2 ]
then
当条件2成立时,执行操作2...
else
当所有条件都不成立时,执行最终操作
fi
示例:判断用户的输入
#!/bin/bash
#判断用户的输入
#Author:root
read -p "Please input a filename: " file
#接收键盘的输入,并赋给变量file
if [ -z $file ]
#判断file变量是否为空
then
echo "Error, please input a filename"
exit 1
#exit后面跟数字,可以指定脚本执行后 $? 的值。后面的代码不会执行。
elif [ ! -e $file ]
#判断file的值是否存在
then
echo "Your input is not a file"
exit 2
elif [ -f $file ]
#判断file的值是否为普通文件
then
echo "$filename is a regular file"
elif [ -d $file ]
#判断file的值是否为目录文件
then
echo "$file is a directory"
else
echo "$file is a special file"
fi