#!/bin/bash # 定义日志函数,用于输出带有时间戳的日志 log() { echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $1" } # 检查是否在 Git 仓库中 if [ ! -d .git ]; then log "当前目录不是一个 Git 仓库." exit 1 fi # 处理空目录,添加 .gitkeep 文件 log "检查空目录..." for dir in $(find . -type d); do if [ -z "$(ls -A "$dir")" ]; then touch "$dir/.gitkeep" log "在空目录 $dir 中添加 .gitkeep 文件。" fi done # 1. 暂存所有更改 log "暂存所有更改..." git add . 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done log "暂存完成." # 2. 提交更改 log "提交更改..." commit_message="[$(date '+%Y-%m-%d %H:%M:%S')]-自动同步" git commit -m "$commit_message" 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done log "提交完成." # 3. 推送更改到远程仓库 log "推送更改到远程仓库..." git push origin main 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done log "推送完成." # 4. 从远程仓库拉取最新代码 log "从远程仓库拉取最代码..." git fetch origin 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done # 5. 解决冲突(如果需要) log "尝试合并远程分支到本地..." git merge origin/main --allow-unrelated-histories -X theirs 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done # 检查是否存在冲突 if [ $? -ne 0 ]; then log "合并冲突,尝试自动解决(以远程仓库为准)..." git checkout --theirs . 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done git add . 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done git commit -m "自动解决冲突" 2>&1 | while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT] $line" done log "冲突解决完成." fi log "同步完成!"