Branch Management — Deleting and Renaming
As you work with Git, branches accumulate. Good branch hygiene means deleting branches after they are merged and renaming branches when their purpose changes.
Deleting a Merged Branch
After merging a feature branch, you should delete it to keep things clean:
git branch -d feature
The -d flag is the safe delete — Git will refuse if the branch has unmerged work.
Force-Deleting an Unmerged Branch
If you want to delete a branch that was never merged (abandoning the work):
git branch -D experiment
The capital -D means "delete no matter what." Use with caution — the commits may become unreachable.
Renaming a Branch
Rename the branch you are currently on:
git branch -m new-name
Rename any branch (you don't need to be on it):
git branch -m old-name new-name
Listing Branches
See all local branches:
git branch
See branches with their last commit message:
git branch -v
See which branches are merged into the current branch:
git branch --merged
See which branches are not merged yet:
git branch --no-merged
These last two commands are helpful for cleanup — branches shown by --merged are usually safe to delete.
Try it!
Practice creating, renaming, and deleting branches:
- Create a file and commit:
echo "hello" > hello.txtthengit add hello.txtthengit commit -m "Initial commit" - Create several branches:
git branch feature-athengit branch feature-bthengit branch experiment - List all branches:
git branch - Rename a branch:
git branch -m feature-a feature-login - Verify the rename:
git branch - Merge one branch (fast-forward):
git merge feature-login - Check which branches are merged:
git branch --merged - Safely delete the merged branch:
git branch -d feature-login - Try to safely delete an unmerged branch:
git branch -d experiment— Git will refuse - Force-delete it:
git branch -D experiment - Verify final state:
git branch
Tips
- Delete branches right after merging them — it is easier than cleaning up later
- Use
git branch --mergedregularly to find branches safe to delete - If you accidentally delete a branch,
git reflogcan help you find the commit and recreate it