目录

Linux 开机自启动脚本机器实现原理

文章简介:linux 设置开机自启动脚本的几种方式

rc.local

使用方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 文件 /etc/rc.d/rc.local
# centos 或者已经配置过此文件
echo "echo 'do HelloWord'" >> /etc/rc.local # 已经有这个文件的时候

# ubuntu 没有 /etc/rc.local,需要创建文件,正确的配置 shebang
printf '%s\n' '#!/bin/bash' 'exit 0' | sudo tee -a /etc/rc.local # 没有这个文件的时候

# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
chmod +x /etc/rc.local
systemctl enable --now rc-local
systemctl status rc-local.service

工作原理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
systemctl cat rc-local.service

[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

可以看到,ConditionFileIsExecutable=/etc/rc.local,当 /etc/rc.local 可执行的时候,systemd 拉起服务的过程中,会执行 /etc/rc.local.

crontab reboot

1
2
echo '@reboot /root/helloworld.sh' >> /etc/crontab
crontab /etc/crontab
1
2
crontab -e
@reboot /root/helloworld.sh