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

这篇博客介绍如何将Shell脚本配置为系统服务,适用于多种操作系统,并涵盖了systemd教程及常见问题解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/bin/bash
# 向一个临时文件中写入配置的内容,两种形式service和systemctl
sudo cat >/tmp/mysql-exporter-systemctl<<EOF
[Unit]
Description=Mysql Exporter
After=network.target
[Service]
ExecStart= ...
[Install]
WantedBy=default.target
EOF

sudo cat >/tmp/mysql-exporter-service<<EOF
#!/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 clamd@scan.service
# 等同于
$ sudo ln -s '/usr/lib/systemd/system/clamd@scan.service' '/etc/systemd/system/multi-user.target.wants/clamd@scan.service'
如果配置文件里面设置了开机启动,systemctl enable命令相当于激活开机启动。

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值