编辑 /etc/rc.local 文件
vim /etc/rc.local
在文件底部加入需要执行的命令,示例如下:
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
ip route delete default via 172.19.79.253 dev eth0 proto dhcp metric 100 #示例
保存,reboot 重启,查看命令是否正常执行。
如果命令没有正常执行,可能是未设置 /etc/rc.local 文件的执行权限:
chmod +x /etc/rc.d/rc.local
chmod +x /etc/rc.local
再次重启,就可以正常自动执行了。
服务指令
systemctl start rc-local.service
systemctl enable rc-local.service
systemctl status rc-local.service
自启动
#!/bin/bash
# 定义要自启动的脚本路径
SCRIPT_PATH="/path/to/your/script.sh"
# 定义要写入到 /etc/rc.local 中的自启动命令
STARTUP_CMD="bash ${SCRIPT_PATH}"
# 将自启动命令写入 /etc/rc.local 中
sed -i "\$i ${STARTUP_CMD}" /etc/rc.local
# 授权脚本执行权限
chmod +x ${SCRIPT_PATH}
# 定义删除脚本和自启动命令的函数
cleanup() {
# 从 /etc/rc.local 中删除自启动命令
sed -i "/${STARTUP_CMD}/d" /etc/rc.local
# 删除脚本文件
rm -f ${SCRIPT_PATH}
}
# 注册清理函数,以便在脚本执行过程中发生异常或者被终止时能够执行
trap cleanup EXIT
# 在脚本中加入要执行的操作,比如:
echo "Hello World"
# 或者启动某个服务,比如:
service nginx start
# 完成自启动脚本的编写