Linux 定时更新 Git 仓库脚本方案(生产级)
✅ 安全可靠 | 日志完整 | 错误隔离 | 多仓库支持 | 无交互设计
📜 一、核心脚本(增强版)
创建文件:/home/youruser/scripts/git_auto_update.sh
#!/bin/bash
# ============================================
# Git 仓库自动更新脚本(支持多仓库/子模块/错误隔离)
# 作者:AI Assistant | 日期:2026-02-04
# ============================================
# ===== 配置区(按需修改)=====
LOG_FILE="/var/log/git_update.log" # 建议:普通用户用 ~/git_update.log
REPO_LIST="/home/youruser/git_repos.txt" # 仓库路径列表(每行一个绝对路径)
TIMEOUT=300 # 单仓库超时时间 (秒)
ENABLE_SUBMODULE=true # 是否更新子模块
# 失败时通知邮箱(留空则不通知)
# =============================
# 初始化日志
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
# 错误处理
handle_error() {
log "❌ [ERROR] $1"
[ -n "$NOTIFY_EMAIL" ] && echo "Git update failed: $1" | mail -s "Git Update Alert" "$NOTIFY_EMAIL"
exit 1
}
# 检查依赖
command -v git >/dev/null 2>&1 || handle_error
[ -f ] || handle_error
[ -d ] || -p 2>/dev/null
SUCCESS_COUNT=0
FAIL_COUNT=0
IFS= -r repo_path || [ -n ];
[[ -z || =~ ^[[:space:]]*# ]] &&
[ ! -d ];
((FAIL_COUNT++))
|| { ; ((FAIL_COUNT++)); ; }
[ ! -d ];
((FAIL_COUNT++))
git status --porcelain | grep -q .;
((FAIL_COUNT++))
git pull --ff-only 2>&1 | -a ;
[ = ] && [ -f ];
git submodule update --init --recursive 2>&1 | -a &&
((SUCCESS_COUNT++))
((FAIL_COUNT++))
- > /dev/null 2>&1
<
[ -gt 0 ] && [ -n ] && \
| mail -s

