Git Branches
A branch is a separate line of work. You can try new ideas on a branch while the main code stays safe.
Why Branches?
Imagine your bakery website is live. You want to add an online order form, but it will take a week. If you work directly on main, the site is half-broken all week. Instead:
- Create a branch called
order-form. - Build the form there, with as many commits as you need.
- When it works, merge it into
main.
Meanwhile, main stays clean, and you can still fix urgent bugs on it.
What a Branch Really Is
A branch is just a small label that points to a commit. When you make a new commit on a branch, the label moves forward to it. That is why creating branches in Git is instant and cheap.
Example
main
|
A --- B --- C
\
D --- E
|
order-formHere main points to commit C, and order-form has two extra commits, D and E.
Basic Branch Commands
| Command | What it does |
|---|---|
git branch | List branches (* marks the current one) |
git branch order-form | Create a branch (but stay where you are) |
git switch order-form | Move to a branch |
git switch -c order-form | Create a branch and move to it |
git branch -m new-name | Rename the current branch |
git branch -d order-form | Delete a merged branch |
git branch -D order-form | Force delete, even if not merged |
Older tutorials use git checkout for switching branches. It still works, but git switch is newer and clearer, so this tutorial uses it.
Creating and Using a Branch
Example
git switch -c order-form
git branchmain * order-form
Now make changes and commit them as usual:
Example
echo "<form>Order here</form>" > order.html
git add order.html
git commit -m "Add order form page"[order-form 5c7e2d1] Add order form page 1 file changed, 1 insertion(+) create mode 100644 order.html
The commit is on order-form only. Switch back to main:
Example
git switch main
lsindex.html style.css
order.html is gone from the folder, because it does not exist on main. Switch back to order-form and it appears again. Git changes your files to match the branch.
Switching with Unsaved Changes
If you have uncommitted changes that would be overwritten, Git refuses to switch:
error: Your local changes to the following files would be overwritten by checkout: index.html Please commit your changes or stash them before you switch branches.
Commit your work first, or use git stash (covered in a later lesson).
Seeing All Branches
Example
git log --oneline --graph --all* 5c7e2d1 (order-form) Add order form page * 8b41d07 (HEAD -> main) Add basic stylesheet * 3f2a9c1 Add home page
Branch Naming Tips
- Use lowercase and hyphens:
order-form,fix-mobile-menu - Many teams use prefixes:
feature/login,fix/footer-link - Keep one branch for one feature or fix
Exercise
Exercise
Which command creates a new branch called login and switches to it?
