← Git

Branches

What is a branch in Git and what is it for?

Show answer — try answering out loud first

A branch is a movable pointer to a commit. It's used to work on something (a feature, a fix) in isolation, without touching the main branch, and then integrate it when it's ready. Creating branches in Git is cheap and fast because it's just creating a pointer.

Many people picture a branch as a "copy" of the project, but it's not. A branch is simply a label that points to a commit. When you make a new commit, the branch you're on advances to point to that commit.

HEAD is another special pointer: it points to the branch (or commit) you're currently on.

What are they for?

  • To develop a feature without breaking the main branch (main).
  • So several people can work in parallel without stepping on each other.
  • To experiment and, if something goes wrong, delete the branch without consequences.

Since a branch is just a pointer, creating it is instant: it doesn't copy files.

# List the branches that exist (the current one has a *)
git branch
# * main
#   nueva-feature

# See which commit each branch points to
git branch -v
# * main         1a2b3c4 Corrige login
#   nueva-feature 5d6e7f8 Agrega registro

# Find out which branch I'm on (HEAD)
git status
# On branch main

# Create a new branch (points to the current commit)
git branch experimento
# The branch exists, but I stay on main until I switch to it

Thinking that a branch duplicates all the project's files, or that working on a new branch automatically "saves" what's on the other one. In reality a branch is just a pointer; uncommitted changes can "travel" with you if you switch branches without having saved them. HEAD (where you are) is also confused with a branch (a label pointing to a commit).

"A branch is a movable pointer to a commit, not a copy of the project. When I make a commit, the branch advances to that commit. HEAD is the pointer that indicates which branch I'm on. I use branches to work on a feature or a fix in isolation without touching main, so the team can work in parallel, and to experiment without fear. Since it's just a pointer, creating branches is instant and very cheap."

Quick challenge

If you create a new branch with git branch feature while on main, which commit does the newly created feature point to?

Show answer

The same commit that main points to at that moment (the current commit, where HEAD is). Both branches point to the same commit until you make a new commit on one of them, at which point only that branch will advance.