Switching, Renaming, and Deleting Branches in Git

In the last blog, we created a feature_chat branch and committed some changes.
In this one, we’ll go deeper and learn how to:

  • Switch back to the main branch.
  • Rename a branch if we made a naming mistake.
  • Delete a branch (with safe and forceful deletion).

Switching Back to Main

When you switch between branches, Git adjusts your working directory to match the snapshot (commit) that branch points to.

git switch main

Now HEAD is pointing to main.


Check files:

ls
# Output: hello.txt
cat hello.txt
# Output:
# hello
# hello again

Notice that chat.txt is missing here because it was added only in the feature branch.


Viewing Commits in Current Branch

By default, git log --oneline shows commits from the current branch.

git log --oneline

To view all commits in the repository (across branches):

git log --oneline --all

Renaming a Branch

Suppose you accidentally named your branch feature_chat but your team follows the convention feature/chat. You can rename it like this:

git branch -m feature_chat feature/chat

Now the branch name is corrected.



Deleting a Branch

Case 1: Branch has unmerged work

If you try deleting a branch with lowercase -d, Git will warn you.

git branch -d feature_chat
# error: The branch 'feature_chat' is not fully merged.

Case 2: Force delete

If you are sure, use uppercase -D:

git branch -D feature_chat

This forcefully removes the branch, even if changes are not merged.


Example: Creating and Deleting a Fresh Branch

If you create a new branch and haven’t added commits to it, you can safely delete it with lowercase -d.

git branch test_feature
git branch -d test_feature

No warnings this time, since there was no unmerged work.


Summary

  • Use git switch branch_name to move between branches.
  • Use git branch -m old_name new_name to rename a branch.
  • Use git branch -d branch_name for safe deletion (only deletes if merged).
  • Use git branch -D branch_name for forceful deletion.

Branch management in Git helps keep your workflow clean and organized.


Keep Learning 🚀

👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.

👉 My YouTube Channel – More videos, more fun, and lots of learning!

👉 📺 Watch this topic in video form

Stay curious, keep coding, and let’s make learning fun together! 🎉