Linux 以 systemd 开机执行 shell 脚本

Linux 以 systemd 开机执行 shell 脚本, 现在大多数的发行版都是使用 systemd 来管理软件的执行。
这样的方式相对比较统一和简单,如:httpd

#启动:
sudo systemctl start httpd
#重启:
sudo systemctl restart httpd
#停止:
sudo systemctl stop httpd
#设置开机启动:
sudo systemctl enable httpd

所以如果我们也想用 systemd 的方式来管理我们自己的 shell 脚本,操作步骤如下:
1.写好 shell 脚本
注意:执行命令前,需要先 cd 到命令文件所在的目录,如:
需要执行 /home/tommy/start 文件

cd /home/tommy
./start

2.书写相关的 service 文件(最重要部分)
只需要修改 ExecStart 和 ExecReload 等为你需要执行的 shell 脚本即可

[Unit]
Description=
Documentation=
After=network.target
Wants=
Requires=

[Service]
ExecStart=/home/downey/test.sh
ExecStop=
ExecReload=/home/downey/test.sh
Type=simple

[Install]
WantedBy=multi-user.target

3.将 service 脚本放到 /etc/systemd/system/ 或者 /usr/lib/systemd/system 目录

cp /路径/test.sh /etc/systemd/system/

4.测试启动

sudo systemctl start test.service

执行完后,需要去检查设置的命令是否有执行。
5.添加开机启动

sudo systemctl enable test.service

6.重启检查一下 设置是否生效

reboot

参考:
https://www.cnblogs.com/downey-blog/p/10473939.html