Shell脚本安装成服务加入系统启动-service

#!/bin/bash
# 向一个临时文件中写入配置的内容,两种形式service和systemctl
sudo cat >/tmp/mysql-exporter-systemctl<sudo cat >/tmp/mysql-exporter-service<#!/bin/bash
case "\$1" in
start)
   ...
   echo \$!>/var/run/[servicename].pid
   ;;
stop)
   sudo kill \`cat /var/run/[servicename].pid\`
   sudo rm -f /var/run/[servicename].pid
   ;;
restart)
   \$0 stop
   \$0 start
   ;;
status)
   if [ -e /var/run/[servicename].pid ]; then
      echo [servicename] is running, pid=\`cat /var/run/[servicename].pid\`
   else
      echo [servicename] is NOT running
      exit 1
   fi
   ;;
*)
   echo "Usage: \$0 {start|stop|status|restart}"
esac

exit 0
EOF

function service_conf(){
  # 判断使用那种形式的配置内容
  if [ -x /usr/bin/systemctl ]; then
    sudo mv /tmp/mysql-exporter-systemctl /usr/lib/systemd/system/[servicename].service
    sudo chmod 754 /usr/lib/systemd/system/[servicename].service
    sudo systemctl daemon-reload
    sudo systemctl enable [servicename].service
  elif [ -x /bin/systemctl ]; then
    sudo mv /tmp/mysql-exporter-systemctl /lib/systemd/system/[servicename].service
    sudo chmod 754 /lib/systemd/system/[servicename].service
    sudo systemctl daemon-reload
    sudo systemctl enable [servicename].service
  else
    sudo mv /tmp/mysql-exporter-service /etc/init.d/[servicename]
    sudo chmod 755 /etc/init.d/[servicename]
  fi
}

service_conf

这个脚本使用于多个操作系统

Systemd 默认从目录/etc/systemd/system/读取配置文件。但是,里面存放的大部分文件都是符号链接,指向目录/usr/lib/systemd/system/,真正的配置文件存放在那个目录。

systemctl enable命令用于在上面两个目录之间,建立符号链接关系。


$ sudo systemctl enable [email protected]
# 等同于
$ sudo ln -s '/usr/lib/systemd/system/[email protected]' '/etc/systemd/system/multi-user.target.wants/[email protected]'
如果配置文件里面设置了开机启动,systemctl enable命令相当于激活开机启动。

与之对应的,systemctl disable命令用于在两个目录之间,撤销符号链接关系,相当于撤销开机启动。

systemd的教程以及可能遇到的问题

你可能感兴趣的:(systemd,shell)