在 CentOS 系统中,可以通过以下方法设置开机自动执行 Shell 脚本。推荐使用 systemd 服务(现代 Linux 系统的标准方式),也可以使用传统的 /etc/rc.local
方法。
方法 1:使用 Systemd 服务(推荐)
1. 创建 Systemd 服务文件
创建一个新的服务单元文件(例如 custom-script.service
):
sudo vi /etc/systemd/system/custom-script.service
2. 编写服务配置
将以下内容粘贴到文件中,按需修改 ExecStart
和 Description
:
[Unit]
Description=Custom Startup Script
After=network.target
[Service]
Type=simple
ExecStart=/path/to/your/script.sh
TimeoutSec=0
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
- 关键参数说明:
ExecStart
: Shell 脚本的绝对路径(必须确保脚本有执行权限)。After=network.target
: 确保脚本在网络就绪后执行。RemainAfterExit=yes
: 脚本执行完成后,服务状态保持为“active”。
3. 设置脚本权限
# 赋予脚本可执行权限
sudo chmod +x /path/to/your/script.sh
4. 启用并启动服务
# 重新加载 systemd 配置
sudo systemctl daemon-reload
# 启用开机自启动
sudo systemctl enable custom-script
# 启动服务(可选,测试脚本)
sudo systemctl start custom-script
# 检查服务状态
systemctl status custom-script
方法 2:使用 /etc/rc.local
(传统方式)
如果系统支持 rc.local
,可按以下步骤操作:
1. 创建或编辑 rc.local
文件
sudo vi /etc/rc.local
2. 添加脚本执行命令
在文件中添加以下内容(确保脚本路径正确):
#!/bin/bash
/path/to/your/script.sh
exit 0
3. 赋予 rc.local
执行权限
sudo chmod +x /etc/rc.local
4. 启用 rc-local
服务(如果未启用)
# 检查是否已存在 rc-local 服务
systemctl status rc-local
# 如果不存在,创建服务文件
sudo vi /etc/systemd/system/rc-local.service
粘贴以下内容:
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.local
TimeoutSec=0
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
5. 启用并启动服务
sudo systemctl daemon-reload
sudo systemctl enable rc-local
sudo systemctl start rc-local
验证和注意事项
-
脚本测试:
- 手动运行脚本确认无误:
sudo /path/to/your/script.sh
- 手动运行脚本确认无误:
-
日志查看:
- 对于 systemd 服务,使用以下命令查看日志:
journalctl -u custom-script -f
- 对于 systemd 服务,使用以下命令查看日志:
-
脚本权限和路径:
- 确保脚本使用绝对路径,避免依赖环境变量。
- 建议将脚本放在
/usr/local/bin/
或专用目录(如/opt/scripts/
)。
-
依赖顺序:
- 如果脚本依赖其他服务(如网络、数据库),在
[Unit]
中添加After=network.target mysqld.service
。
- 如果脚本依赖其他服务(如网络、数据库),在
常见问题排查
-
脚本未执行:
- 检查脚本权限:
chmod +x /path/to/script.sh
。 - 检查 systemd 服务状态:
systemctl status custom-script
。 - 检查日志:
journalctl -u custom-script
。
- 检查脚本权限:
-
/etc/rc.local
不生效:- 确认系统支持
rc.local
(CentOS 7+ 默认不启用,需手动配置)。
- 确认系统支持
-
脚本环境问题:
- 在脚本中指定 Shell 解释器(如
#!/bin/bash
)。 - 避免依赖交互式环境变量,使用绝对路径。
- 在脚本中指定 Shell 解释器(如
通过以上方法,Shell 脚本会在系统启动时自动执行。推荐优先使用 systemd 服务,它提供更精细的控制和日志跟踪。