Trung BìnhGit iconGit

Tại sao `git pull` thường tạo merge commit không cần thiết và cách fix với `--rebase`?

Vấn đề: bạn có local commits chưa push.

Teammate đã push lên remote. git pull = git fetch + git merge → tạo merge commit "Merge branch 'main' of github.com/..." không có ý nghĩa.

bash
# git log trông giống:
# * Merge branch 'main' of ... ← không có ý nghĩa
# |\ 
# | * teammate: feat: add cart
# * | your: feat: add login
# |/
# * old commit

Fix: dùng git pull --rebase:

bash
git pull --rebase origin main
# = git fetch + git rebase origin/main
# Kết quả: history linear, commits của bạn replay trên top

Set làm default:

bash
git config --global pull.rebase true
# Hoặc per-repo:
git config pull.rebase true

Trường hợp pull --rebase gặp conflict:

bash
# Resolve conflict trong file
git add resolved-file.ts
git rebase --continue
# Hoặc abort:
git rebase --abort  # về trạng thái trước pull

Khi nào dùng git pull (merge) thay vì rebase:
- Branch đã có merge commits quan trọng (merge commit là intentional)
- Long-lived feature branch muốn preserve merge history

Tip: git pull --rebase --autostash tự động stash local changes trước khi rebase, unstash sau.

Xem toàn bộ Git cùng filter theo level & chủ đề con.

Mở danh sách Git