1. rc-local
基于 Debian 的 Linux 系统默认支持 rc-local.service 服务,这个服务主要用来在系统启动时运行用户自定义的脚本命令等。
2. 配置
要想使用 rc-local.service 服务在系统启动时运行用户自定义的脚本命令,首先需要在 /etc 目录下创建 rc.local 文件(若已创建则跳过创建)并修改可执行权限,然后设置该服务开机自启:
$sudo touch /etc/rc.local
$sudo chmod 755 /etc/rc.local
2.1 修改rc-local.service
增加[Install]字段
$ nano /lib/systemd/system/rc-local.service
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
执行指令:
$ sudo systemctl enable rc-local.service
3. 添加开机自启脚本
打开 /etc/rc.local 文件,往其中添加运行自定义脚本的命令即可。
$ cat /etc/rc.local
#!/bin/sh -e
#
####
exit 0
【注】/etc/rc.local 以及自定义脚本中都不能使用系统变量(比如 $HOME,原因在于其执行自定义脚本时并没有继承系统变量)。
4. 查看脚本执行结果
# sudo systemctl status rc-local.service