欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

systemd系统开机运行shell脚本

Linux 迷途小书童 4年前 (2019-12-05) 7403次浏览 0个评论

软硬件环境

  • ubuntu 18.04 64bit

前言

本文讨论的是在systemd系统的linux发行版(后期的ubuntucentos都是)中如何实现开机自动执行shell脚本,在shell中你可以添加任何你想要开机执行的任务。

准备工作

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

#!/bin/bash

date >> /home/xugaoxiang/test.txt

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

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

systemd服务

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

[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内容

systemd shell

重启系统之后再次查看

systemd shell

自动开机执行shell就可以完成了

喜欢 (1)

您必须 登录 才能发表评论!