天天看点

if

目录

  • if
    • 转换
    • 文件比对
    • 整数数值比较
张贺,多年互联网行业工作经验,担任过网络工程师、系统集成工程师、LINUX系统运维工程师
           

if语句可以转成一行由&&、|| 组成的的语句,例如:

if [ -f /etc/passwd ];then
        echo "password file yes!"
else
        echo "password file no!"
fi
           

可以转换成:

[ -f /etc/passwd ] && echo "password file yes" || echo "password file no"
           

或者转换成:

[ ! -f /etc/passwd ] && echo "password file no" || echo "password file yes"
           

参数 说明 示例
r 文件存在且有读权限为真 [ -r file]
w 文件存在且有写权限为真 [ -w file]
x 文件存在且有执行权限为真 [ -x file]
f 文件存在且是普通文件为真 [ -f file]
d 目录存在则为真 [ -d file]
e 如果文件或目录存在则为真 [ -e file]
-s 文件非空为真 [ -s file]

记忆说明:一共7个,前五个不用记忆,最后一个e就是-f和-d结合,-s就仅仅是探测文件是否为空。

例子:交互式备份数据库

#!/bin/bash
#====================================
#Date:2018/3/2
#Author:zhanghe
#Wechat:zhanghe@15069028807
#Effect:interactive backup database
#====================================

DestPath=/backup/mysql
M_User=root
M_Pass="zhang@00"

[ ! -d $DestPath ] && mkdir -p DestPath
# [ -d DestPath ] || mkdir -p DestPath

read -p "Please Input backup sql_name: " DB
/usr/bin/mysqldump -u$M_User -p$M_Pass --single-transaction -R -B $DB > $DestPath/${DB}_$(date +%F).sql
if [ $? -eq 0 ];then
	echo "---------------------"
	echo "backup $DB successful!"
	echo "---------------------"
fi
           

-eq 等于为真 [ 1 -eq 9]
-ne 不等于为真 [ 1 -ne 9]
-gt 大于为真 [ 1 -gt 9]
-lt 小于为真 [ 1 -lt 9]
-ge 大于等于为真 [ 1 -ge 9]
-le 小于等于为真 [ 1 -le 9]
#!/bin/bash
#====================================
#Date:2018/3/2
#Author:zhanghe
#Wechat:zhanghe@15069028807
#Effect:service run or down
#====================================

[ $# -ne 1 ] && echo "please input services name!" && exit 1
systemctl status "$1" > /dev/null
if [ $? -eq 0 ];then
        echo "$1 active!"
elif [ $? -eq 4 ];then
        echo "no $1 services!"
else
        echo "$1 is down!"
fi
           
Disk_Free=$(df -h | grep "/$" | awk '{print $5}' | awk -F % '{print $1}')
if [ $Disk_Free -gt 80 ];then
        echo "Disk Is Use:${Disk_Free}%" > /tmp/disk_use.txt
        mail -s "Disk_Free" [email protected] < /tmp/disk_use.txt
fi
           
Mem_Use=$(free -m | sed -n 2p | awk '{print $3/$2*100}')
if [ ${Mem_Use%.*} -ge 80 ]
then
        echo "Memory IS ERROR ${Mem_Use%.*}%"
else
        echo "Memory IS OK ${Mem_Use%.*}%"        
fi
           
上一篇: Redis(1)