有時我們需要將特定操作封裝成服務,通過服務啟動停止,例如nginx的啟動停止,service nginx start 或者service nginx stop
下面我們將編寫一個demo
cd /etc/init.d/
sudo vi test,建立一個service名稱為test的服務
加入下面模版代碼
#! /bin/sh ### BEGIN INIT INFO # Provides: reboot # Required-Start: # Required-Stop: # Default-Start: # Default-Stop: 6 # Short-Description: Execute the reboot command. # Description: ### END INIT INFO PATH=/sbin:/usr/sbin:/bin:/usr/bin . /lib/lsb/init-functions do_stop () { # Message should end with a newline since kFreeBSD may # print more stuff (see #323749) log_action_msg "Will now restart" reboot -d -f -i } case "$1" in start) nohup /etc/init.d/test.sh >> b.log 2>&1 & ;; stop) do_stop ;; *) echo "Usage: $0 start|stop" >&2 exit 3 ;; esac
可以根據需要編寫start方法以及stop方法
賦予執行權限
sudo chmod +x /etc/init.d/test
然后我們再寫一個shell測試腳本
sudo vi test.sh
#!/bin/bash int=1 while(( $int<=5 )) do date >> ~/a.log sleep 1 # let "int++" done
賦予執行權限
sudo chmod +x /etc/init.d/test.sh
接下來,我們啟動服務
service test start
查看服務是否已經啟動
tail -f ~/a.log
會看到不斷的打印時間
這說明我們的腳本已經以服務的形式啟動起來了。