将shell脚本添加到开机启动

  有时我们需要将shell脚本作为开机自启动服务,这样能避免出现问题后重新开机还需要再挨个启动服务

脚本内容如下

#!/bin/bash
#chkconfig: 2345 90 10
#description:auto_run
echo "success!" >> /root/test.txt

#chkconfig: 2345 90 10
#description:auto_run
以上两行标注蓝色的代码必须要加上,否则在执行"chkconfig --add xxx.sh"时会报如下错误:
service test.sh does not support chkconfig

chkconfig参数说明:

参数说明
0关机
1单用户模式
2无网络支持的多用户模式
3有网络支持的多用户模式
4保留,未使用
5有网络支持有X-Window支持的多用户模式
6重新引导系统,即重启
90启动优先级,优先级范围是0-100,数字越大,优先级越低。
10启动优先级,优先级范围是0-100,数字越大,优先级越低。

编写完脚本后,将脚本移动到/etc/rc.d/init.d目录

 mv /root/test.sh /etc/rc.d/init.d

赋予脚本执行权

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

添加脚本到开机自启动项目中

chkconfig --add test.sh
chkconfig test.sh on

配置好这些后就可以了,可以reboot一下测试结果,我重启两次后结果如下:

cat test.txt
success!
success!
shell 脚本注册为开机启动,通常是在Linux或macOS系统完成的,这样每次系统启动时,该脚本会自动运行。以下是两种常见的做法: 1. **Systemd(适用于Linux)**: - 使用文本编辑器打开`/etc/systemd/system/your_script.service`文件(如果文件不存在,需要创建),然后添加类似下面的内容: ```bash [Unit] Description=Your Script Startup After=network.target [Service] Type=simple ExecStart=/path/to/your/script.sh Restart=always User=<your_username> [Install] WantedBy=multi-user.target ``` 替换 `/path/to/your/script.sh` 为你的脚本的实际路径,`<your_username>` 为你希望以哪个用户身份运行脚本。 - 保存文件并更新权限: ``` sudo systemctl daemon-reload sudo systemctl enable your_script.service ``` - 确认服务已启用: ``` sudo systemctl start your_script.service ``` 2. **Launchd(适用于Mac OS)**: - 打开终端,创建一个新的plist文件(`.plist`格式),例如 `~/Library/LaunchAgents/com.yourname.script.plist`: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.yourname.script</string> <key>ProgramArguments</key> <array> <string>/path/to/your/script.sh</string> </array> <key>RunAtLoad</key> <true/> <key>UserName</key> <string><your_username></string> </dict> </plist> ``` 再次替换路径和用户名。 - 给文件加上权限: ``` sudo chown root:<your_username> ~/Library/LaunchAgents/com.yourname.script.plist sudo chmod 644 ~/Library/LaunchAgents/com.yourname.script.plist ``` - 加载服务: ``` launchctl load ~/Library/LaunchAgents/com.yourname.script.plist ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值