Git三路合并后删除分支的底层机制及示意图解析
git branch -d issue53 Under the Hood & Post-Deletion Repository Structure Great question—this cuts to the core of how Git handles branches, which is key to moving beyond just typing commands and actually understanding what’s happening in your repository. Let’s break this down clearly:
1. Underlying Mechanics of git branch -d
First, let’s recap a foundational truth about Git branches: they’re just lightweight pointers to commit objects. Unlike some other version control systems, Git doesn’t create full copies of your code for each branch—each branch is just a tiny text file in your .git/refs/heads/ directory that stores the 40-character hash of the branch’s latest commit.
When you run git branch -d issue53 (after merging issue53 into master to create commit c6), here’s exactly what Git does:
- First, a safety check: Git verifies that the
issue53branch’s commits are fully "reachable" from your currently checked-out branch (in this case,master). Since you mergedissue53intomaster, all commits onissue53are now part ofmaster’s commit history, so this check passes. If you tried to delete an unmerged branch with-d, Git would throw an error to prevent accidental data loss (use-Dinstead if you intentionally want to delete an unmerged branch). - Delete the branch pointer: Git removes the
.git/refs/heads/issue53file. That’s it—no commits are deleted, no code is removed. The commits that were onissue53(let’s sayE,F,Gleading up toc6) are still fully present in your repository.
Important note: Those issue53 commits will only be removed eventually if they become completely unreachable—meaning no branch, tag, or Git reflog entry points to them (or to any commit that points to them). Until then, they’re safe, and you could even restore the issue53 branch later by running git branch issue53 <hash-of-G> if you needed to.
2. Post-Deletion Repository Structure
Let’s visualize this with a simple ASCII schematic:
Before deleting issue53 (post-merge):
A -- B -- C -- D -- c6 (master) \ / E -- F -- G (issue53)
masterpoints to the merge commitc6issue53points to commitG(the last commit on that branch before merging)c6has two parent commits:D(the lastmastercommit pre-merge) andG
After deleting issue53:
A -- B -- C -- D -- c6 (master) \ / E -- F -- G
- The
issue53pointer is gone, but commitsE,F,Gare still fully reachable viac6’s parent reference. Your repository’s commit graph remains intact—you’ve just removed one of the labels pointing to a specific commit.
内容的提问来源于stack exchange,提问作者Andrew S

