Files
o.nmgjg.com.cn/git_sync.sh

72 lines
2.2 KiB
Bash
Executable File

#!/bin/bash
# 定义日志函数,用于输出带有时间戳的日志
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $1"
}
# 检查是否在 Git 仓库中
if [ ! -d .git ]; then
log "当前目录不是一个 Git 仓库,请在 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 "同步完成,所有操作结束。"