Introduction to Git Branches
So far, we have seen how commits are created and how logs can be viewed.
Now we will go one step ahead and visualize branches — where HEAD points, what each branch points to, and how these pointers move after every action.
Why Do We Need Branches?
Think about real apps: they start simple (only posts), then someone says, “let’s add chat,” later voice, then video calls. If we change the stable app directly and it breaks, users suffer.
The safe way is to keep main stable, make a copy (branch), build the feature there, and merge only after testing.
Create the repository
mkdir Project2
cd Project2
git init
By default Git creates a branch named main (older repos often used master).
First file and first commit (on main)
echo "Hello World" > hello.txt
git add hello.txt
git commit -m "First commit"
git log --oneline
Example output:
af9916f First commit
Diagram — after first commit (HEAD on main):
Second commit on main
Our hello file grows a bit.
echo "Hello again" >> hello.txt
git add hello.txt
git commit -m "Second commit"
git log --oneline
Example output:
9672151 Second commit
af9916f First commit
Diagram — second commit chained to first:
Create a feature branch (chat)
We want to add a chat module but keep main safe.
git branch feature_chat
Right now both branches point to the same latest commit.
Diagram — branch created; both pointers same place:
Switch to the feature branch
git switch feature_chat
From now on, new commits go to feature_chat.
Diagram — HEAD moved to feature branch:
Add the chat feature and commit (on feature branch)
We write a small file to represent the chat module.
echo "Chat function added" > chat.txt
git add chat.txt
git commit -m "Added chat feature"
git log --oneline
Example output:
60bd6b5 Added chat feature
9672151 Second commit
af9916f First commit
Diagram — new commit on feature (reference-style blocks):
Read this like a timeline:
af9916f→9672151on main. We branched and moved feature_chat forward to60bd6b5, while main still points to9672151.
Summary
- We started a repo and made two commits on main (
af9916f→9672151). - We created feature_chat, which initially pointed to the same commit as main.
- After switching, HEAD moved to feature_chat and our new commit
60bd6b5advanced only that branch. - Visual diagrams after each step make it clear where HEAD and branch pointers live.
In the next blog, we will switch back to main and learn how to merge the feature branch safely — with another set of simple diagrams.
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! 🎉