Renaming and Deleting Branches
Asha's experiments leave a trail: test, vegan-pancakes, pancake-v2. Some names were vague and some branches are finished. Tidying them keeps git branch readable, and Git has a safety catch so tidying never costs you work.
The rule
Rename with
-m; delete with-d, which refuses to lose unmerged work.
Renaming. A branch name is only a label, so renaming is instant and changes no commits:
git branch -m better-name # rename the branch you are on
git branch -m test oat-pancakes # rename another branch: old, then newA common real rename: older repositories often start on a branch called master. If you would rather match the main used everywhere else, git branch -m master main renames it in one step, and all its commits stay exactly as they were.
Deleting. Once a branch's work is merged, the label is no longer needed:
git branch -d vegan-pancakes-d is the safe delete. If the branch has commits that are not merged into your current branch (or its upstream), Git refuses with a message that the branch is not fully merged. That protects work you may have forgotten.
When you truly want to throw an experiment away, use the capital letter:
git branch -D pancake-v2 # force delete, merged or notTwo more rules:
- You cannot delete the branch you are currently on. Switch to another branch first.
- Deleting a branch removes the label, not the commits that other branches still point to. Merged work stays in history.
Branches on a remote. Everything above is local. If a branch was shared on GitHub, renaming or deleting it locally does not change the remote copy. You will meet remotes properly in a later section; for now, know that the remote side needs its own step, such as:
git push origin --delete vegan-pancakesThe shortcut
Before deleting, ask "Is this work anywhere else?" Run git branch --merged to list branches whose commits are already inside the current branch. Those are safe for -d. Anything missing from that list needs a decision: merge it, or knowingly force-delete it with -D.
Stand on main
git switch main, because you cannot delete the branch you are on.
The trap is reaching for -D by habit. The refusal from -d is Git asking "are you sure?"; read it before overriding it.
Drills
Answer fast — trust the rule.
Which command renames the current branch to oat-pancakes?
git branch -d pancake-v2 fails with "not fully merged". What does that mean?
Asha is on vegan-pancakes and runs git branch -d vegan-pancakes. What happens?
Asha deletes a local branch that also exists on GitHub. What happens to the GitHub copy?
Remember
- Rename with
-m; delete with-d, which refuses to lose unmerged work. - Check
git branch --mergedfirst; force with-Donly on purpose. - You cannot delete the branch you are on, and remote branches need their own step.
