如何用 cron 與 shell script 之間用法

前陣子在鑽研伺服器自動重啟服務,發現在寫 shell script 的時候,若要加入排程 cron 的話,有一些需要注意。不然的話,你寫的 shell script 沒辦法按照你自已的想法重新啟動。

shell script 內容加入判斷,若程式啟用的服務無法連線時,會透過 cron 排程進行重啟服務。所以,以下問題是經過查詢以及測試,得出來的結果

記錄下:

shell script 內容如下

#!/bin/bash
 
export LD_LIBRARY_PATH=/root/pingtool/
#source LD_LIBRARY_PATH="/root/pingtool/"
 
PATH=$PATH:/sbin/
 
#count=`/root/pingtool/IOTCAPIs_Measure_Client UDP -p 192.96.200.112 | grep spend |awk '{print $17}'`
count1=`/root/pingtool/IOTCAPIs_Measure_Client UDP -p 127.0.0.1 -o 10240 | grep "Recv =" | awk '{ORS="" ;print $13 }'|cut -d ',' -f 1`
if  [ "$count1" == "0" ]; then
        /usr/bin/service iotc stop > /dev/null 2>&1
        /usr/bin/service iotc start > /dev/null 2>&1
echo iotc restart
else
        echo $count1 > /dev/null 2>&1
fi
count2=`/root/pingtool/IOTCAPIs_Measure_Client TCP -p "127.0.0.1" | grep IOTC_Measure| awk '{ORS="" ;print $2 }'`
if  [ "$count2" == "MSG_HELLO1_R!" ]; then
 
        echo $count2 > /dev/null 2>&1
 
else
 
        /usr/bin/service iotc stop > /dev/null 2>&1
        /usr/bin/service iotc start > /dev/null 2>&1
echo iotc restart
fi

參考連結:

https://stackoverflow.com/questions/13521774/starting-a-service-upstart-from-a-shell-script-from-a-cron-job

處理過程:

shell script 程式內容 – 加入PATH=$PATH:/sbin/ 環境變數之後,就能順利透過 cron 執行排程

結論:

經過測試,伺服器程式都會順利執行程式