Skip to main content

Branching

Branches let you work on a change in isolation without touching main. You can experiment, break things, and throw the branch away — main is never affected until you deliberately merge.

What a Branch Is

A branch is a lightweight pointer to a commit. When you create a branch, Git just makes a new pointer. No files are copied. No history is duplicated.

ABCmainDEfeature-greetingHEAD

In this diagram:

  • main points to commit C — the last commit on the main line.
  • feature-greeting branched from C and has two new commits (D, E).
  • HEAD is a special pointer that tracks which branch you are currently on. Here it points to feature-greeting.

main is untouched. You can switch back to it any time and it will be exactly at C.


See Your Branches

git branch

Output:

* main

The * marks your current branch.


Create and Switch to a New Branch

git switch -c feature-greeting

-c means "create." This creates the branch and immediately switches to it.

Confirm you switched:

git branch

Output:

* feature-greeting
main

The older syntax (git checkout -b feature-greeting) still works. git switch is the modern, more readable alternative.


Make Commits on the Branch

echo "Hello from the feature branch!" > greeting.txt
git add greeting.txt
git commit -m "Add greeting file"

Your branch now has a commit that main does not.


Switch Back to Main

git switch main

Notice greeting.txt disappears from your folder. It exists on feature-greeting, not on main. The files are not deleted — they are just not part of the main snapshot.

Switch back to your feature branch:

git switch feature-greeting

greeting.txt reappears.


Push the Branch to GitHub

git push -u origin feature-greeting

Go to your GitHub repo. In the branch dropdown you will see feature-greeting alongside main.


Summary

CommandWhat it does
git branchList branches
git switch -c <name>Create and switch to a new branch
git switch <name>Switch to an existing branch
git push -u origin <name>Push branch to GitHub (first time)
Donate to this project