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."
fimysql

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
需注意目錄是否存在,有時會被別人刪除,因此要加上若是不存在就添加目錄的程序.sql

思考:判斷系統內存大小,低於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/nullbash

相關文章
相關標籤/搜索