鄂破机看 发表于 2018-8-27 11:13:24

3.shell脚本编程之语句控制

# cat testservice.sh  
#!/bin/bash
  
#
  
#chkconfig: - 50 50
  
#description: test service scipt
  
#
  

  
prong=$(basename $0)
  
lockfile=/var/lock/subsys/$prong
  

  
case $1 in
  
start)
  if [ -f $lockfile ];then
  echo "$prong is running yet."
  else
  touch $lockfile
  [ $? -eq 0 ] && echo "start $prong finished."
  fi
  ;;
  
stop)
  if [ -f $lockfile ];then
  rm -f $lockfile
  [ $? -eq 0 ] && echo "stop $prong finished."
  else
  echo "$prong is not running."
  fi
  ;;
  
restart)
  if [ -f $lockfile ];then
  rm -f $lockfile
  echo "stop $prong finished."
  touch $lockfile
  
      echo "start $prong finished."
  else
  touch $lockfile
  echo "start $prong finished."
  fi
  ;;
  
status)
  if [ -f $lockfile ];then
  echo "$prong is running"
  else
  echo "$prong is stopped"
  fi
  ;;
  
*)
  echo "Usage: $prong {start|stop|restart|status}"
  exit 1
  
esac
  

  
#================================================================================
  
# 复制到 /etc/init.d/ 目录下:
  
# cp testservice /etc/init.d/
  
# ls /etc/init.d/
  
functionsnetconsolenetworkREADMEtestservice.sh
  

  
# 加入到 SysV 服务中去,使用 service 命令管控
  
# chkconfig --add testservice
  
# chkconfig --list testservice
  

  
注意:该输出结果只显示 SysV 服务,并不包含原生 systemd 服务。SysV 配置数据可能被原生 systemd 配置覆盖。
  
      如果您想列出 systemd 服务,请执行 'systemctl list-unit-files'。
  
      欲查看对特定 target 启用的服务请执行
  
      'systemctl list-dependencies '。
  

  
testservice    0:关1:关2:关3:关4:关5:关6:关
  

  
# ll /etc/init.d/testservice
  
-rw-r--r-- 1 root root 798 3月   2 13:42 /etc/init.d/testservice
  

  
# 给脚本一个执行权限
  
# chmod +x /etc/init.d/testservice
  

  
# 服务脚本测试如下
  
# service testservice start
  
start testservice finished.
  
# service testservice start
  
testservice is running yet.
  
# service testservice restart
  
stop testservice finished.
  
start testservice finished.
  
# service testservice stop
  
stop testservice finished.
  
# service testservice restart
  
start testservice finished.
  
# service testservice res
  
Usage: testservice {start|stop|restart|status}
  
# ls /var/lock/subsys/
  
networktestservice
  
# service testservice stop
  
stop testservice finished.
  

  
# 注意:通过服务控制的脚本都会在启动完成后在 /var/lock/subsys/ 下创建一个锁文件
  
# service testservice stop
  
stop testservice finished.
  
# ls /var/lock/subsys/
  
network
  
# service testservice status
  
testservice is stopped
  
# service testservice start
  
start testservice finished.
  
# ls /var/lock/subsys/
  
networktestservice


页: [1]
查看完整版本: 3.shell脚本编程之语句控制