系统相关
首页 > 系统相关> > shell单分支if条件句语法详解与生产案例详解

shell单分支if条件句语法详解与生产案例详解

作者:互联网

比较两个数大小
方法一:
[oracle@dbserver ~]$ vi fi_o1.sh
a=$1
b=$2
if [ $a -gt $b ]
then
echo "yes,$a >= $b"
fi
if [ $a -le $b ]
then
echo "yes,$a <= $b"
fi
[oracle@dbserver ~]$ sh fi_o1.sh 4 5
yes,4 <= 5
方法二:
[oracle@dbserver ~]$ vi fi_o1.sh
a=$1
read -p "please input two number:" a b
if [ $a -gt $b ]
then
echo "yes,$a >= $b"
fi
if [ $a -le $b ]
then
echo "yes,$a <= $b"
fi
[oracle@dbserver ~]$ sh fi_o1.sh
please input two number:4 5
yes,4 <= 5
判断一个文件是否存在,如果不存在就创建此文件程序.
方法一:
[root@dbserver ~]# cat if4.sh
#!/bin/sh
FILEPATH="/server/scripts"
if
[ -e "$FILEPATH/if3.sh" ]
then
echo "$FILEPATH/if3.sh is exist."
fi

if [ ! -e "$FILEPATH/if3.sh" ]
then
[ ! -d $FILEPATH ] && mkdir -p $FILEPATH
[ -d $FILEPATH ] && {
cd $FILEPATH
touch if3.sh
echo "if3.sh is touched."
}
fi
执行结果:
[oracle@dbserver ~]$ sh if4.sh
/server/scripts/if3.sh is exist.
[root@dbserver ~]# rm -f /server/scripts/if3.sh
[root@dbserver ~]# sh if4.sh
if3.sh is touched.
方法二:
[root@dbserver ~]# vi fi4.sh
#!bin/bash
FILEPATH="/server/scripts"
[ ! -d $FILEPATH ] && mkdir -p $FILEPATH
cd $FILEPATH
if [ -f $FILEPATH/if3.sh ]
then
echo "if3.sh is exist"
exit 0
else
touch $FILEPATH/if3.sh
echo "$FILEPATH/if3.sh is made completely"
执行结果:
[root@dbserver ~]# sh fi4.sh
if3.sh is exist
[root@dbserver ~]# rm -f /server/scripts/if3.sh
[root@dbserver ~]# sh fi4.sh
/server/scripts/if3.sh is made completely
[root@dbserver ~]# sh fi4.sh
if3.sh is exist
查看执行步骤的具体过程
[root@dbserver ~]# sh -x fi4.sh
+ FILEPATH=/server/scripts
+ '[' '!' -d /server/scripts ']'
+ cd /server/scripts
+ '[' -f /server/scripts/if3.sh ']'
+ touch /server/scripts/if3.sh
+ echo '/server/scripts/if3.sh is made completely'
/server/scripts/if3.sh is made completely
备份文件,并将结果发送给某人邮件
[ ! -d /server/backup ] && mkdir /server/backup
mysqldump -uroot -p123 -A -B >/server/backup/a.sql
[ ! -f server/backup/a.sql ] && mail -s "bak faile" asdfasdf@qq.com
需注意目录是否存在,有时会被别人删除,所以要加上如果不存在就添加目录的程序.

思考:判断系统内存大小,低于1250M就进行邮件报警.
处理这个问题,先回顾以下两个知识点,
awk后面的变量NF和$NF有什么区别?
{print NF}也有{print $NF}
前者是输出域的个数,后者是输出最后一个字段的内容.
Crontab命令的构成为 时间+动作,其时间有 分、时、日、月、周 五种.
[root@dbserver ~]# vi judge_system.sh
cur_free=free -m|awk '/buffers\// {print $NF}'(注释:最外面那两个“`”为esc下面那个键)
chars="current memory is $cur_free."
if [ $cur_free -lt 1250 ]
then
echo $chars
echo $chars|mail -s "$chars" 1012079728@qq.com
fi
执行结果:
[root@dbserver ~]# sh judge_system.sh
current memory is 1213.
每分钟检查一次程序,
[root@dbserver ~]# crontab -e
no crontab for root - using an empty one
#judge
* * * * * /bin/sh /root/judge_system.sh >&/dev/null

标签:shell,if3,dbserver,sh,server,详解,scripts,条件句,root
来源: https://blog.51cto.com/12991611/2629451