Branches

Git · Practical · 10 min

Branches let you develop features and fixes in isolation without disturbing working code.

In Git a branch is nothing more than a tiny file holding a commit ID. When you commit on a branch, that pointer moves forward to the new commit. `HEAD` says which branch you are on, so Git knows which pointer to move.

Because branches are just pointers, creating one is instant and costs nothing, which is why Git workflows use them for every feature, bug fix and experiment.

The modern commands (Git 2.23+):

  • git switch -c feature-x: create a branch at the current commit and switch to it.
  • git switch main: switch back. Your working tree is updated to that branch's snapshot.
  • git switch -c fix origin/fix: create a local branch from a remote one (plain git switch fix does this automatically if exactly one remote has it).
  • git branch: list local branches; -a includes remote-tracking ones; -vv shows upstreams.
  • git branch -d feature-x: delete a branch that is merged; -D forces deletion of an unmerged one.
  • git branch -m new-name: rename the current branch.

The older git checkout does all of this too, plus restoring files, which is why switch and restore were split out; you will still see checkout in many guides.

Switching with uncommitted changes works if they don't clash with the target branch; otherwise Git refuses rather than losing your work. Commit or stash first.

If you check out a commit or tag directly (git switch --detach v1.2), you are in detached HEAD: HEAD points at a commit, not a branch. New commits there belong to no branch, so create one with git switch -c if you want to keep them.

Example

git switch -c feature/login        # create + switch
echo "form" > login.html
git add login.html && git commit -m "Add login form"
git switch main                     # login.html disappears from disk
git branch -vv
#   feature/login 7d1c0aa Add login form
# * main          3f9a2c1 [origin/main] Fix totals
git log --oneline --graph --all
git branch -d feature/login         # error: not fully merged
git branch -D feature/login         # force delete

Remember

  • A branch is a pointer to a commit; HEAD names the current branch
  • git switch -c creates and switches; git branch -d deletes merged branches
  • Detached HEAD: commits made there need a branch to be kept

Watch out for

  • Doing work in detached HEAD and switching away — those commits become unreachable (recoverable only via reflog).

Check yourself

  1. What actually happens on disk when you create a branch?
  2. You commit while on branch feature. What moves?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell