1.格式
if [ 条件判断式 ];then ##如果条件成立,执行下面的程序
程序
fi ##if语句结束的标志
或者
if [ 条件判断式 ]
then
程序
fi
2.注意
if语句使用fi结尾
[ 条件判断式 ]:中括号与条件判断式直接必须有空格
3.练习1:判断登录用户是否是root
[root@catyuan ~]# vim if1.sh
#!/bin/bash
test=$(env | grep USER | cut -d "=" -f 2) ##从env环境变量中过滤出当前的登录用户,并赋值给test
if [ "$test" == "root" ];then ##判断test变量是否等于root
echo "user is root" ##如果等于则输出这句话
fi
[root@catyuan ~]# chmod 755 if1.sh
[root@catyuan ~]# ./if1.sh
user is root
4.练习2:判断分区使用率
思路:
[root@catyuan ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 20G 3.8G 16G 20% /
devtmpfs 898M 0 898M 0% /dev
tmpfs 912M 0 912M 0% /dev/shm
tmpfs 912M 9.1M 903M 1% /run
tmpfs 912M 0 912M 0% /sys/fs/cgroup
/dev/sda1 197M 152M 45M 78% /boot
tmpfs 183M 32K 183M 1% /run/user/0
[root@catyuan ~]# df -h | grep /dev/sda3
/dev/sda3 20G 3.8G 16G 20% /
[root@catyuan ~]# df -h | grep /dev/sda3 | awk '{print $5}'
20%
[root@catyuan ~]# df -h | grep /dev/sda3 | awk '{print $5}' | cut -d "%" -f 1
20
编写脚本:
[root@catyuan ~]# vim if2.sh
#!/bin/bash
test=$( df -h | grep /dev/sda3 | awk '{print $5}' | cut -d "%" -f 1 ) #从查看文件系统的结果过滤出sda3的一行(就是/分区所在的那行),使用awk命令输出前面结果的第五行,再使用cut命令来指示分隔符为%,过滤出第一列的结果。
if [ "$test" -ge "90" ];then ##如果test变量大于等于90
echo "/ is full" ##则输出这句话
fi
[root@catyuan ~]# chmod 755 if2.sh
[root@catyuan ~]# ./if2.sh