Branches
A branch is an independent line of development. You create one to build a feature or fix a bug without touching the working code on main. If the idea works, you merge it in; if not, you delete the branch.
What a branch really is
A branch is just a movable pointer to a commit. Creating one is instant and costs nothing. HEAD is a pointer to the branch you're currently on.
main
↓
A ─── B ─── C
↖
feature ← HEAD (you are here)When you commit, the branch HEAD points to moves forward to the new commit.
Creating and switching branches
Run this, then look at the commit graph that appears:
Notice: after git switch main, contact.html disappears from your folder (ls). Git swaps the files to match the branch you're on. Switch back with git switch feature/contact and it reappears.
| Command | Does |
|---|---|
git branch |
List branches (* marks the current one) |
git branch <name> |
Create a branch (but stay where you are) |
git switch <name> |
Switch to a branch |
git switch -c <name> |
Create and switch |
git checkout -b <name> |
The older way to create and switch (still very common) |
git branch -d <name> |
Delete a merged branch |
git branch -D <name> |
Force-delete an unmerged branch |
git branch -m <new> |
Rename the current branch |
Branches diverge
When both branches get new commits, history forks:
The graph now shows two lines. In the next lessons you'll merge them back together.
Switching with uncommitted changes
Git won't switch branches if that would overwrite your uncommitted work:
git stash shelves your uncommitted changes temporarily, and git stash pop brings them back. It's perfect when you need to switch tasks quickly.
Branch naming conventions
feature/login-page,fix/cart-total,docs/api-guide,chore/upgrade-deps- Include a ticket number if your team uses them:
feature/JIRA-142-dark-mode - Lowercase, hyphens, short and descriptive
Detached HEAD
If you git checkout <commit-id> instead of a branch, you're in detached HEAD state: looking at an old snapshot without being on a branch. That's fine for looking around. If you make commits there, create a branch (git switch -c rescue) to keep them.
Practice
Simulate a real workflow: create a repo with one commit on main. Create feature/header and make two commits there. Switch to main and make one commit. Then create feature/footer from main with one commit. Check the commit graph: you should see three lines.
1.What is a Git branch, technically?
2.Which command creates a new branch and switches to it?