CentOS 系统 Shell 脚本开机自启动方法详解

🚨 重要提醒

在 CentOS 系统中设置 Shell 脚本开机自启动,主要有以下几种方法,推荐使用 systemd 服务方式(适用于 CentOS 7+):

方法一:使用 systemd 服务(推荐)

步骤1:准备 Shell 脚本

创建脚本文件并赋予可执行权限:

bash 复制代码
sudo vi /path/to/your-script.sh
sudo chmod +x /path/to/your-script.sh

步骤2:创建 systemd 服务文件

在 /etc/systemd/system/ 目录下创建服务文件:

bash 复制代码
sudo vi /etc/systemd/system/your-service.service

步骤3:编辑服务文件内容

ini 复制代码
[Unit]
Description=Your Service Description
After=network.target
[Service]
Type=simple
ExecStart=/path/to/your-script.sh
Restart=on-failure
User=root
[Install]
WantedBy=multi-user.target

步骤4:启用并启动服务

bash 复制代码
sudo systemctl daemon-reload
sudo systemctl enable your-service.service
sudo systemctl start your-service.service

步骤5:验证服务状态

bash 复制代码
sudo systemctl status your-service.service

方法二:使用 rc.local 文件

步骤1:确保 rc.local 可执行

bash 复制代码
sudo chmod +x /etc/rc.d/rc.local

步骤2:编辑 rc.local 文件

bash 复制代码
sudo vi /etc/rc.d/rc.local

步骤3:添加脚本路径

在文件末尾添加:

bash 复制代码
/path/to/your-script.sh

方法三:使用 chkconfig(适用于 CentOS 6)

步骤1:将脚本移动到 init.d 目录

bash 复制代码
sudo mv /path/to/your-script.sh /etc/init.d/
sudo chmod +x /etc/init.d/your-script.sh

步骤2:添加 chkconfig 支持

在脚本开头添加:

bash 复制代码
#!/bin/sh
# chkconfig: 2345 90 10
# description: Your service description

步骤3:启用服务

bash 复制代码
sudo chkconfig --add your-script.sh
sudo chkconfig your-script.sh on

方法四:使用 crontab

bash 复制代码
sudo crontab -e

添加:

bash 复制代码
@reboot /path/to/your-script.sh

注意事项

  1. 路径问题:所有路径必须使用绝对路径
  2. 权限问题:确保脚本有执行权限
  3. 环境变量:systemd 环境下环境变量可能不完整,必要时在脚本中加载环境变量
  4. 网络依赖 :如果脚本需要网络,确保在 systemd 服务文件中配置 After=network.target

推荐使用 systemd 方式,因为它提供了更好的服务管理、日志记录和故障恢复机制。

相关推荐
dingdingfish1 小时前
TLPI 第52章 读书笔记:POSIX Message Queues
linux·mq·ipc·posix·message·tlpi
wacsii2 小时前
【Linux进程(五)】进程控制全解析:从创建、终止、等待到程序替换
linux·服务器
七夜zippoe3 小时前
Nexent Linux 部署:用 deploy.sh
linux·服务器·docker·部署·ai智能体·nexent
去码头整点薯条983 小时前
NFS服务器
linux·运维·服务器
蜗牛一步步往上爬4 小时前
第一章 初识Linux shell
linux·运维·服务器
拂拉氏4 小时前
【知识讲解】 Linux线程中锁的认识
linux·互斥锁
无足鸟ICT4 小时前
【RHCA+】系统调优配置文件
linux·服务器
时间的拾荒人6 小时前
Shell 脚本核心语法详解(下篇):流程控制、函数、重定向与文件包含
linux·运维·服务器·bash·脚本编程
蜗牛一步步往上爬6 小时前
第四章 更多的bash shell命令
linux·开发语言·bash
进击的荆棘7 小时前
Linux网络——网络基础概念
linux·运维·服务器·网络