Create, Switch, and Delete Git Branches (with Visual HEAD Pointers)

In the last video, we modified branches, switched, and deleted them.
Now we will create branches using different options, switch immediately, see how HEAD moves, list local branches, and delete branches safely.


Starting point: on main

Assume our repo already has a couple of commits and we are on main.

Diagram — HEAD on main (sample history):



Option 1: Create a branch, then switch

1) Create the branch (you stay on current branch)

git branch test_branch

Right now you are still on main. Only a new pointer was created at the same commit.

Diagram — new branch created; both pointers same commit:


2) Switch to that branch

git switch test_branch

Diagram — HEAD moves to test_branch:


Branch list (local only):

git branch

The branch with a * is your current branch.


Option 2: Create and switch in one command (modern)

git switch -c test_branch_1

This creates test_branch_1 and switches to it immediately.

Diagram — HEAD on the newly created branch:


Tip: -c means “create”. If the name already exists, Git will stop; -C (capital) recreates by moving the pointer (use with care).


Option 3: Old but common syntax

You can do the same using checkout (older style, still seen in many guides):

git switch main      # move back to main first
git checkout -b test_branch_3

Diagram — all three branches point to the same commit; HEAD on test_branch_3:


Recommendation: For learning and team consistency, prefer git branch (create/manage) + git switch (move between). Use checkout -b only if a script or older guide requires it.


Deleting branches safely

You cannot delete the branch you are currently on (even with -D). First switch away, then delete.

1) Switch to main

git switch main

2) Delete merged branches

git branch -d test_branch
git branch -d test_branch_1
git branch -d test_branch_3

If Git says “not fully merged” and you’re sure, use force:

git branch -D test_branch_3

Diagram — back to clean state (only main remains):



Summary

  • git branch <name> creates a branch; you stay where you are.
  • git switch <name> moves HEAD to that branch.
  • git switch -c <name> creates and switches in a single step (modern way).
  • git checkout -b <name> is the older equivalent of create+switch.
  • List local branches with git branch.
  • You cannot delete the checked-out branch. Switch, then -d (safe) or -D (force).

In the next video, we’ll compare branches and revisit diff: branch-to-branch comparisons with clear visuals.


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! 🎉