Skip to content

Instantly share code, notes, and snippets.

@chinlung
Created March 13, 2025 00:53
Show Gist options
  • Save chinlung/820c86bfc6da70fb6c22c6cd63604e5e to your computer and use it in GitHub Desktop.
Save chinlung/820c86bfc6da70fb6c22c6cd63604e5e to your computer and use it in GitHub Desktop.
這個腳本會自動處理所有本地分支的更新,並在遇到衝突時跳過該分支
#!/bin/bash
# 獲取遠端倉庫的最新數據
git fetch origin
# 記錄當前分支
current_branch=$(git rev-parse --abbrev-ref HEAD)
# 檢查是否有未提交的更改,並暫存
stashed=false
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "檢測到未提交的更改,正在暫存..."
git stash push -m "Temporary stash for branch updates"
stashed=true
fi
# 儲存衝突的分支列表
conflicted_branches=()
# 遍歷所有本地分支並嘗試更新
for branch in $(git branch | sed 's/\*//'); do
# 檢查遠端是否存在對應分支
if git rev-parse --verify "origin/$branch" > /dev/null 2>&1; then
echo "正在處理分支:$branch"
git checkout "$branch"
# 檢查本地分支是否落後於遠端分支
if [ $(git rev-list --count "$branch"..origin/"$branch") -gt 0 ]; then
# 嘗試快進合併
if git merge --ff-only origin/"$branch"; then
echo "成功更新分支 $branch"
else
echo "分支 $branch 出現衝突,跳過更新"
conflicted_branches+=("$branch")
# 回退合併
git merge --abort
fi
else
echo "分支 $branch 已與 origin/$branch 一致,無需更新"
fi
fi
done
# 切換回原始分支
echo "切換回原始分支:$current_branch"
git checkout "$current_branch"
# 如果有暫存的更改,恢復它們
if [ "$stashed" = true ]; then
echo "恢復未提交的更改..."
git stash pop
fi
# 提示衝突的分支
if [ ${#conflicted_branches[@]} -gt 0 ]; then
echo "以下分支因衝突未成功更新:"
for conflicted in "${conflicted_branches[@]}"; do
echo "- $conflicted"
done
else
echo "所有分支更新完成,無衝突"
fi
echo "腳本執行完畢!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment