想讓自己的程式有「服務」的架勢,只要借用系統自帶的 functions 函式庫,幾行就能做出 start/stop/restart 的介面。
#!/bin/bash
. /etc/init.d/functions
function usage()
{
echo "$0 {start|stop|restart}"
}
if [ $# -ne 1 ]
then
echo "ttt"
usage
exit 1
fi
case $1 in
start)
action "start..." /bin/true
;;
*)
usage
;;
esac
存成 test_1.sh 後測試:
[root@test]# sh test_1.sh
ttt
test_1.sh {start|stop|restart}
[root@test]# sh test_1.sh start
start... [ OK ]
第一行 . /etc/init.d/functions 用 source 的方式載入系統函式庫,讓腳本取得 action 等工具函式;第二行 action "start..." /bin/true 才是真正產生 [ OK ] 的魔術師。它的原理很單純:把提示文字與要執行的命令一起交給 action,命令回傳 0 就顯示 OK,否則顯示 FAILED。因此只要把 /bin/true 換成 /bin/false,就能得到失敗的示範:
action "fail..." /bin/false # 顯示 [FAILED]
把這個模式套用到 stop、restart 上,再補上 PID 檔處理與狀態判斷,你的腳本就和系統服務沒有兩樣了。