Trung BìnhGit iconGit

Branch bị xóa nhầm, chưa merge vào đâu cả. Recover như thế nào?

Branch chỉ là pointer đến commit. Xóa branch không xóa commits — chỉ xóa pointer. Commits vẫn tồn tại trong git object store cho đến khi git gc chạy.

Recovery qua reflog:

bash
git reflog --all | grep "feature/deleted-branch"
# Output: abc123 refs/heads/feature/deleted-branch@{0}: commit: feat: last work

# Recreate branch tại commit đó:
git checkout -b feature/deleted-branch abc123
# hoặc:
git branch feature/deleted-branch abc123

Nếu không nhớ tên branch:

bash
git reflog | grep "checkout: moving from"
# Tìm lần cuối bạn checkout khỏi branch đó

Nếu reflog không có (branch trên remote bị xóa):

bash
git fetch origin  # nếu remote còn lưu
# Hoặc hỏi teammate — họ có thể có local copy

Nếu đã git gc chạy:

bash
git fsck --lost-found
# Tìm "dangling commit" — đó là commits không còn branch nào trỏ đến
for sha in .git/lost-found/commit/*; do git log --oneline -1 $sha; done  # xem commits tìm được

Phòng tránh: trước khi xóa branch, push lên remote hoặc tag commit cuối: git tag backup/feature-before-delete <branch>.

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

Mở danh sách Git