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 branchSwitch to an existing branch
$ git switch feature/search-filtersCreate and switch in one step
$ git checkout -b hotfix/login-timeoutListing 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.
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
Exercise: Git Branch
What is a Git branch, technically?