systemd系统如何开机运行shell脚本

原文出处 http://xugaoxiang.com/post/114

软硬件环境

  • ubuntu 16.04 64bit

前言

本文讨论的是在systemd系统的linux发行版中如何实现开机自动执行shell脚本。

准备脚步

创建一个shell脚本test.sh,将系统时间写入文件

#!/bin/bash

date >> /home/xugaoxiang/test.txt

然后给脚本加上执行的权限

chmod a+x /home/xugaoxiang/test.sh

systemd服务

在/etc/systemd/system目录下创建一个文件,内容如下

[Unit]
After=mysql.service

[Service]
ExecStart=/home/xugaoxiang/test.sh

[Install]
WantedBy=default.target

其中[Unit]标签下的After是指本服务是在mysql.service执行完之后才会启动;[Install]标签下的WantedBy是指服务的分类,比如上面写的系统默认的,还有比如说蓝牙相关的、打印机相关的等等。所以的服务及类别管理都可以在/etc/systemd/system下找到,更多的配置可以通过man systemd.service来查询。

chmod 664 /etc/systemd/system/test.service
systemctl daemon-reload
systemctl enable test.service

执行完毕后会在/etc/systemd/system/default.target.wants下创建test.service的软连接文件

测试

在重启系统之前可以通过命令

systemctl start test.service

查看/home/xugaoxiang/test.txt内容

重启系统之后再次查看

猜你喜欢

转载自blog.csdn.net/djstavav/article/details/79429244