>

In Linux, service scripts are usually located in /etc/init.d/ directory (In CentOS 7, it is /usr/lib/systemd/system/my.service), if we don’t know how to write such script we can always go to that directory and find a ‘template’ for study.

Below is a simple start up service script, it controls the start, restart and stop of Python Flask service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/sh

host=http://localhost:4000

cur_dir=`pwd`
cur_pid=$$

function start_hexo() {
test $(pwd) = "/e/god/juniway" || (echo "not in directory /e/god/juniway"; exit 1)
(hexo g >/dev/null 2>&1 && nohup hexo s &> out 2>&1) & (sleep 6; chrome http://localhost:4000)
}

function stop_hexo() {
test $(pwd) = "/e/god/juniway" || (echo "not in directory /e/god/juniway"; exit 1)
ps ux | grep -E '/usr/bin/sh|node' | awk -v var="$cur_pid" '$1!=var{print $1}' | xargs kill >/dev/null 2>&1
# don't kill current shell, otherwise restart will fail after executing stop_hexo()
}

function restart_hexo() {
stop_hexo
start_hexo
}

function status_hexo() {
echo -e "cur_pid:"$cur_pid"\n"
ps ux | grep -E '/usr/bin/sh|node'
}

function main() {
action=$1
case $action in
'start')
start_hexo
;;
'stop')
stop_hexo
;;
'restart')
restart_hexo
;;
'status')
status_hexo
;;
*)
echo "Bad argument!"
echo "Usage: $0 {start|stop|restart|status}"
;;
esac
}

main $*