当前位置: 代码网 > 服务器>服务器>Linux > 设置Shell脚本开机自启的方法和实例

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

2024年05月15日 Linux 我要评论
1. 准备一个shell脚本#!/bin/sh#chkconfig: 2345 22 80#description: filebeat serviceecho "start test ...";tou

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

以上就是设置shell脚本开机自启的方法和实例的详细内容,更多关于shell脚本开机自启的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com