linux开机运行程序的方式有很多种,纪录使用systemd的方式。

编辑systemd脚本

直接复制下方命令运行即可,命令会在/etc/systemd/system创建rc-local.service文件,并且写入内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cat > /etc/systemd/system/rc-local.service <<EOF
[Unit]
Description=/etc/rc.local
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target
EOF

编写需要运行的shell脚本

如需要运行/root/start.sh,则创建/root/start.sh文件。

1
2
3
4
5
cat > /root/start.sh <<EOF
#!/bin/sh -e
#这里填写开机需要运行的命令
exit 0
EOF

更改权限

1
chmod +x /root/start.sh

编辑开机启动脚本

1
2
3
4
5
6
cat > /etc/rc.local <<EOF
#!/bin/sh -e
cd root
sh start.sh
exit 0
EOF

更改权限

1
chmod +x /etc/rc.local

设置开机启动

1
2
systemctl enable rc-local
systemctl start rc-local.service

使用小技巧

可以在/root/start.sh再次调用其他命令,达到设置多个shell脚本开机启动的目的。