Git Branch: List, Rename and Delete Branches Safely
Inspect and rename a branch
In the fresh cleanup lab, main has a commit and draft points to the same commit. List local branches and rename draft. Names must be valid and the target name must not already exist.
git branchgit branch -vgit branch -m draft documentationgit branch --listThe asterisk marks the active branch in this single-worktree fixture. Rename changes the reference name, not its commit ID, and does not rename a hosted branch.
Delete only a branch you have checked
The renamed branch points to the same commit as main, so its work is already reachable from main. The --merged filter tests ancestry against the specified revision. In this lab no upstream is configured.
The local branch name disappears; main still identifies the same commit. In real repositories -d checks the configured upstream if one exists, otherwise HEAD. Verify the intended integration target explicitly. A branch checked out in a worktree cannot be deleted normally.
Respect refusal to delete unmerged work
Create a new branch with a unique commit, then return to main. Check the branch ancestry before asking Git to delete it.
git switch -c unfinishedprintf "Future work\n" > idea.txtgit add -- idea.txtgit commit -m "Save future idea"git switch maingit branch --no-merged maingit branch -d unfinishedThe final command intentionally fails in this fixture. Keep unfinished until its work is integrated or otherwise preserved. Force deletion can remove the only convenient reference to valuable commits; do not use -D as a routine fix. Deleting a name is not immediate object deletion, but recovery is not guaranteed.
Practice
Identify which branch in a graph is reachable from main before proposing deletion. Explain why a refusal is useful.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Branch: List, Rename and Delete Branches Safely — knowledge check
Reason about branch references, snapshots and safe local operations.
What does git branch -m draft documentation change?
What does git branch --merged main test?
A branch has no upstream and is not reachable from current HEAD. What does -d ordinarily do?
What if a branch has a configured upstream?
What should you do when an unfinished branch deletion is refused?