Tour of Git
Branching & Merging / Lesson 2.8

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:

  1. Create a file and commit: echo "hello" > hello.txt then git add hello.txt then git commit -m "Initial commit"
  2. Create several branches: git branch feature-a then git branch feature-b then git branch experiment
  3. List all branches: git branch
  4. Rename a branch: git branch -m feature-a feature-login
  5. Verify the rename: git branch
  6. Merge one branch (fast-forward): git merge feature-login
  7. Check which branches are merged: git branch --merged
  8. Safely delete the merged branch: git branch -d feature-login
  9. Try to safely delete an unmerged branch: git branch -d experiment — Git will refuse
  10. Force-delete it: git branch -D experiment
  11. Verify final state: git branch

Tips

  • Delete branches right after merging them — it is easier than cleaning up later
  • Use git branch --merged regularly to find branches safe to delete
  • If you accidentally delete a branch, git reflog can help you find the commit and recreate it
🎯

Goal

Create a branch, rename it, then delete the old-named branch after merging

Terminal
$

No commits yet. Run `git init` and create your first commit.