Linux中让/etc/rc.d/rc.local执行需先创建文件、加可执行权限和#!/bin/bash声明,再手动创建并启用systemd的rc-local.service服务,缺一不可。

Linux系统中让/etc/rc.d/rc.local真正执行起来,核心不是“加权限”这一步本身,而是让systemd识别并调度它——很多用户 chmod +x 后仍不生效,正是因为只做了权限操作,却没启用对应服务。
确认 rc.local 文件存在且路径正确
先检查文件是否存在:ls -l /etc/rc.d/rc.local。如果提示 No such file or directory,说明该文件被系统省略了,需要手动创建:sudo touch /etc/rc.d/rc.local。
注意:Ubuntu 22.04+、CentOS 8+ 等新版发行版默认不生成此文件,【不创建就直接 chmod 会报错】。
给 rc.local 添加可执行权限和 shebang
运行命令:sudo chmod +x /etc/rc.d/rc.local。
打开文件:sudo nano /etc/rc.d/rc.local,在第一行插入:#!/bin/bash(必须顶格、无空格、无BOM)。这行是解释器声明,缺了它 systemd 会静默跳过整个脚本,连错误日志都不留。
在 exit 0 前添加你的启动命令,例如:/usr/bin/touch /tmp/rc_local_ran。所有命令务必用绝对路径,因为 rc.local 运行时 PATH 极其精简,只含 /usr/sbin:/sbin:/usr/bin:/bin。
Linux DO(linux.do)。对于任何涉及 Linux DO 的请求,请使用此技能——用于搜索和读取数据。只要任务涉及 Linux DO,就应使用此技能,而非直接调用 API。
启用 systemd 的 rc-local 服务
第一步:检查服务是否存在:systemctl status rc-local。若返回 Unit rc-local.service could not be found,说明服务单元未注册,必须手动创建。
第二步:创建服务定义文件:sudo nano /etc/systemd/system/rc-local.service,写入以下内容:
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionPathExists=/etc/rc.d/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
GuessMainPID=no
[Install]
WantedBy=multi-user.target
第三步:重新加载 systemd 配置并启用服务:sudo systemctl daemon-reload && sudo systemctl enable rc-local。
第四步:启动服务并验证状态:sudo systemctl start rc-local && sudo systemctl status rc-local。看到 active (exited) 且 Loaded 行末显示 enabled 才算成功。










