Learn

Working with branches

Git

Create a branch, switch to it, merge it. Why you (almost) never work directly on main.

A branch is a parallel line of development. You start from the current state of main, make your changes on it, and merge once you are ready. This lesson covers creating, switching, and merging a branch.

Why not work directly on main

main is the reference branch. If you commit broken code there, everyone sees that broken code. By creating a dedicated branch, you isolate your work: you experiment, break things, fix them, and only integrate when things are clean.

The basic rule: main should always be in a stable, deployable state. Everything else happens on branches.

Create a branch

shell
git branch my-feature

This command creates the branch, but you stay on main. To create and switch in one step:

shell
git switch -c my-feature

See your branches

shell
git branch

The asterisk * marks the current branch. To also see remote branches:

shell
git branch -a

Switch between branches

shell
git switch my-feature
git switch main

Commits on the branch

Once on your branch, commit normally. These commits only exist on this branch.

shell
echo "new feature" > feature.txt
git add feature.txt
git commit -m "add feature.txt"

Merge the branch into main

When the work is done, switch back to main and merge.

shell
git switch main
git merge my-feature

Git creates a merge commit that unites the two histories. See the result with:

shell
git log --oneline --graph

Delete the merged branch

Once merged, the branch is no longer needed. Delete it to keep the repo clean:

shell
git branch -d my-feature

The -d (safe delete) flag refuses deletion if the branch has not been merged yet. A useful guard.

git-scm.com - git branch git-scm.com - git switch

What comes next

With branches under control, you can connect your repo to GitHub and start working with a team.

Check off steps to unlock what comes next

Back to course