A branch is a lightweight, movable pointer to a commit. From Git’s glossary:
A “branch” is a line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch.
Branches allow you to:
Develop features independently
Experiment without affecting stable code
Organize work by context (features, bugs, releases)
Collaborate with multiple streams of development
Git branches are incredibly lightweight - just 41 bytes (a reference to a commit SHA-1 and a newline). This makes branch operations nearly instantaneous.
# List local branches$ git branch feature-x* main bugfix-123# List with commit info$ git branch -v feature-x 750b4ea Add new feature* main 4ccb6d7 Update docs bugfix-123 2a1b3c4 Fix critical bug# List all branches (including remote)$ git branch -a feature-x* main remotes/origin/main remotes/origin/feature-x
The * indicates your current branch (where HEAD points).
Normally HEAD stores the name of a branch. However, Git also allows you to check out an arbitrary commit that isn’t necessarily the tip of any particular branch. The HEAD in such a state is called “detached”.
Entering detached HEAD:
$ git checkout abc123Note: switching to 'abc123'.You are in 'detached HEAD' state...
In this state:
HEAD points directly to a commit, not a branch
New commits aren’t associated with any branch
Switching branches may make these commits unreachable
/* * Creates a new branch, where: * - name is the new branch name * - start_name is the name of the existing branch that * the new branch should start from * - force enables overwriting an existing branch * - track causes the new branch to be configured to merge * the remote branch that start_name tracks */void create_branch(struct repository *r, const char *name, const char *start_name, int force, int clobber_head_ok, int reflog, int quiet, enum branch_track track, int dry_run);
# Commits in feature-x not in main$ git log main..feature-x# Files changed between branches$ git diff main...feature-x# Check if branch is merged$ git branch --merged main
Git worktrees let you check out multiple branches simultaneously:
# Create worktree for feature branch$ git worktree add ../feature-x-worktree feature-x# Work in the new directory$ cd ../feature-x-worktree$ git log --oneline# Remove when done$ git worktree remove ../feature-x-worktree