1. 准备一个Shell脚本

#!/bin/sh
#chkconfig: 2345 22 80
#description: Filebeat Service
echo "start test ...";
touch /data/aaa.txt
sleep 3
echo "test over ..."

1.1 注意

#!/bin/sh
#chkconfig: 2345 22 80
#description: Filebeat Service

这三行必须放在脚本前三行。否则可能会出现 服务 xxx.sh 不支持 chkconfig 或者 service xxx.sh does not support chkconfig

2. 复制脚本到init.d目录

如果脚本没有做统一管理的话,也可以直接在init.d目录下创建脚本。

# 注意这里脚本路径改成自己的路径,如果直接在init.d目录下创建的可忽略这条命令
cp /data/test.sh /etc/init.d/test.sh

3. 设置脚本权限

chmod +x /etc/init.d/test.sh

4. 添加服务

chkconfig --add test.sh

执行无效的话 尝试切换到 /etc/init.d/ 目录下执行。

5. 测试是否成功添加

#  test.sh 换成你自己的脚本名
chkconfig --list test.sh

2345 开启则成功添加开机自启。在这里插入图片描述




以下为补充科普,可不看

6. 设置Shell脚本开机自启的方法和实例

在Linux系统中,自启动脚本是管理和配置系统的重要手段之一。本章节将介绍如何设置Shell脚本在系统启动时自动运行,并将关注于不同Linux系统下的实现方法。

6.1 Shell脚本自启动原理

Shell脚本的自启动可以通过将脚本添加到系统启动时执行的目录或通过系统服务管理器实现。下面将分别介绍这两种方法的原理。

6.1.1 添加到启动目录

Linux系统在启动时会自动执行特定目录中的脚本文件。通过将Shell脚本添加到这些目录中,可以实现开机自启动。

  • /etc/rc.d/rc.local目录: 在一些传统的Linux发行版中,可以将脚本添加到/etc/rc.d/rc.local文件中。这个文件在系统启动时最后被执行,可以用于自定义启动脚本。
# 将脚本路径添加到rc.local文件
echo "/path/to/your/script.sh" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local

6.1.2 使用系统服务管理器

现代Linux系统通常使用systemd或其他服务管理器来控制系统服务。通过创建一个systemd服务单元,可以方便地管理Shell脚本的自启动。

  • 创建systemd服务单元文件:
# /etc/systemd/system/your-service.service
[Unit]
Description=Your Service Description
After=network.target

[Service]
ExecStart=/path/to/your/script.sh
Restart=always
User=your_username

[Install]
WantedBy=multi-user.target
  • 启用并启动服务:
# 启用服务
sudo systemctl enable your-service

# 启动服务
sudo systemctl start your-service

6.2 不同Linux系统的具体实现方法

6.2.1 Ubuntu/Debian

在Ubuntu和Debian系统中,可以通过systemd服务管理器实现Shell脚本的自启动。

# 创建systemd服务单元文件
sudo nano /etc/systemd/system/your-service.service

在文件中添加上述提到的服务单元内容,保存并退出。然后启用并启动服务。

sudo systemctl enable your-service
sudo systemctl start your-service

6.2.2 CentOS/RHEL

在CentOS和RHEL系统中,可以使用systemd或将脚本添加到/etc/rc.d/rc.local文件。

使用systemd

# 创建systemd服务单元文件
sudo nano /etc/systemd/system/your-service.service

添加服务单元内容,保存并退出,然后启用并启动服务。

sudo systemctl enable your-service
sudo systemctl start your-service

添加到rc.local

# 将脚本路径添加到rc.local文件
echo "/path/to/your/script.sh" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local

6.2.3 Arch Linux

Arch Linux也使用systemd作为服务管理器。同样,可以通过创建systemd服务单元文件实现自启动。

# 创建systemd服务单元文件
sudo nano /etc/systemd/system/your-service.service

添加服务单元内容,保存并退出,然后启用并启动服务。

sudo systemctl enable your-service
sudo systemctl start your-service
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐