Creating branches is the foundation of safe development in Git.
Instead of working directly on main, you create branches to:
- build features
- fix bugs
- experiment safely
- prepare releases
git branch feature👉 This creates a new branch named feature
It does NOT switch to the branch
Before creating a branch:
A --- B --- C (main)
After:
A --- B --- C (main, feature)
👉 Both branches point to the same commit
gitGraph
commit id: "A"
commit id: "B"
commit id: "C"
branch feature
When you run:
git branch featureGit creates a file:
.git/refs/heads/featureInside it:
<commit-hash>
Example:
a1b2c3d4e5f6...
👉 This means:
feature → commit C
Steps Git performs:
- Reads current commit from HEAD
- Creates new reference file
- Stores commit hash in it
No files are copied.
Branch creation is instant because Git only creates a pointer
git branch featuregit branch feature <commit-hash>Use when starting from older history.
git branch feature maingit switch -c featureOR
git checkout -b featuregit branchgit branch feature-logingit branch bugfix-headergit branch hotfix-paymentgit branch backup-before-refactorgit branch test-old abc1234git init
echo "Hello" > file.txt
git add .
git commit -m "Initial commit"
git branch feature
git branchOutput:
* main
feature
| Command | Behavior |
|---|---|
| git branch feature | creates only |
| git switch feature | switches |
| git switch -c feature | creates + switches |
You created branch but still on main
Fix:
git switch featureAlways check:
git branch
git log --onelineAvoid:
test1
abc
branch2
Use:
feature-login
bugfix-navbar
hotfix-payment
- create branch from correct base
- use clear names
- keep branches focused
- verify before committing
Q: What happens when you create a branch in Git?
Answer:
When you create a branch, Git creates a new reference inside
.git/refs/heads/that points to the current commit. No files are copied. It is just a pointer to a commit, which is why branch creation is very fast.
git branch = create pointer git switch = move pointer
git branch namecreates a branch- does NOT switch automatically
- stored inside
.git/refs/heads/ - points to current commit
- Does
git branch featureswitch branches? - Where is the branch stored internally?
- Why is branch creation fast?
- How do you create + switch in one command?
Go to: 03-switch-branch.md
- new pointer created
- points to current commit
This does NOT switch branch.
👉 03-switch-branch.md