Git Branch

Git branches let you split off an independent line of development, work on it in isolation, and bring it back into your project only when it is ready.

What a Branch Actually Is

Unlike some older version control systems, a Git branch is not a full copy of your project. It is simply a lightweight, movable label pointing at a specific commit. When you commit new work on a branch, Git just moves that label forward to point at the new commit. This is why creating and switching branches in Git is close to instantaneous, no matter how large the repository is, and why teams are encouraged to branch constantly rather than sparingly.

Creating and Switching Branches

The `git branch <name>` command creates a new branch pointer at your current commit but does not move you onto it. To actually move your working directory and HEAD onto a branch, use `git switch` (the modern, purpose-built command) or the older `git checkout`. Both update the files in your working directory to match the tip of the target branch, so commit or stash any pending changes first.

Create a branch, then list branches

$ git branch feature/search-filters
$ git branch

Switch to an existing branch

$ git switch feature/search-filters

Create and switch in one step

$ git checkout -b hotfix/login-timeout

Listing Branches

Plain `git branch` lists local branches only, with an asterisk marking the one you're on. A handful of flags reveal more of the picture, from remote-tracking branches to which ones are safe to delete because their work has already landed elsewhere.

CommandShows
git branchLocal branches, current one starred
git branch -aLocal and remote-tracking branches
git branch -rRemote-tracking branches only
git branch -vLocal branches with their last commit
git branch --mergedBranches already merged into HEAD

Deleting and Renaming Branches

Once a branch's work has been merged, delete it with `git branch -d <name>`. Git refuses this if the branch has commits that aren't reachable from anywhere else, protecting you from silently losing work. To delete regardless, for an abandoned experiment, use the force flag `-D` instead.

  • git branch -d old-feature - safe delete, blocked if unmerged
  • git branch -D old-feature - force delete, no safety check
  • git branch -m new-name - rename the branch you're currently on
  • git push origin --delete old-feature - delete the branch on the remote too
Note: Prefix branch names with a category, like feature/, bugfix/, or release/2.4. Most Git hosting UIs group branches by these prefixes automatically, which keeps a busy repository navigable.
Note: git branch -D deletes the pointer immediately with no confirmation. If no other branch or tag references those commits, they become unreachable and are eventually garbage-collected, recoverable only briefly via git reflog.

Exercise: Git Branch

What is a Git branch, technically?