提示词
我用的Rocky Linux release 9.5 (Blue Onyx) 现在写一个shell脚本可以定时每5秒检测/jh_system/www/wwwroot/tapp.99atest.cn里面有没有index.zip文件,如果有就删除/jh_system/www/wwwroot/tapp.99atest.cn里面的index.html文件和static目录,然后unzip index.zip,然后删除index.zip实现更新项目,然后做到systemctl服务里面,服务名字叫jhh5
下面是ai给的
好的!下面给你一套在 Rocky Linux 9.5 上可直接用的方案:一个 Bash 脚本 + systemd service + systemd timer,每 5 秒检查一次是否有 index.zip,若有就按你的流程解包更新并清理压缩包。服务名按你要求叫 jhh5。
- 准备更新脚本
创建脚本 /usr/local/bin/jhh5_update.sh(可改,但记得与后面的 unit 一致):
!/usr/bin/env bash
/usr/local/bin/jhh5_update.sh
set -euo pipefail
TARGET_DIR="/jh_system/www/wwwroot/tapp.99atest.cn"
ZIP_NAME="index.zip"
LOCK_FILE="/var/lock/jhh5.lock"
防止并发(timer 每5秒跑一次,如果上次还没跑完,这次直接退出)
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
exit 0
fi
确认目录存在
if [[ ! -d "TARGET_DIR"
exit 0
fi
cd "$TARGET_DIR"
如果没有 zip,直接退出
if [[ ! -f "$ZIP_NAME" ]]; then
exit 0
fi
可选:记录日志到 journald
echo "jhh5: Detected TARGET_DIR"
删除 index.html 和 static 目录(若存在)
rm -f index.html
rm -rf static
解压(覆盖同名文件)
需要系统已安装 unzip:dnf install -y unzip
unzip -o "$ZIP_NAME" >/dev/null
删除压缩包
rm -f "$ZIP_NAME"
echo "jhh5: Update finished"
赋予执行权限:
sudo chmod +x /usr/local/bin/jhh5_update.sh
注:脚本已用 flock 防并发、set -euo pipefail 防止异常时继续执行。
- 创建 systemd 服务(oneshot)
新建 /etc/systemd/system/jhh5.service:
[Unit]
Description=JH H5 auto updater (checks and applies index.zip updates)
Wants=jhh5.timer
[Service]
Type=oneshot
ExecStart=/usr/local/bin/jhh5_update.sh
把脚本输出写入 journald
StandardOutput=journal
StandardError=journal
如果需要以特定用户运行(例如 nginx 用户),取消下一行注释并改成合适的用户
User=nginx
Group=nginx
[Install]
WantedBy=multi-user.target
- 创建 systemd 定时器(每 5 秒触发一次)
新建 /etc/systemd/system/jhh5.timer:
[Unit]
Description=Run jhh5.service every 5 seconds
[Timer]
开机 5 秒后首次执行
OnBootSec=5s
之后每次 jhh5.service 运行结束后 5 秒再触发
OnUnitActiveSec=5s
Unit=jhh5.service
AccuracySec=1s
防止积压:如果错过触发时间,不补跑
Persistent=false
[Install]
WantedBy=timers.target
说明:用 *.timer 实现“每 5 秒执行一次”。相比让 service 自己 while true; sleep 5 更稳、更易管理和停止。
重新加载并启用/启动
sudo systemctl daemon-reload
sudo systemctl enable --now jhh5.timer常用查看/调试命令
查看当前定时器状态:
systemctl status jhh5.timer
查看最近一次执行日志:
journalctl -u jhh5.service -n 50 --no-pager
立即手动触发一次(不等 5 秒):
systemctl start jhh5.service
停止定时器(暂停周期执行):
systemctl stop jhh5.timer