Branch
In Git, a branch is a sequence of commits that represents the evolution of the project (or a specific feature) over time. There's always at least one branch in a repository, usually called the main
branch. You can create new branches to work on new features or bug fixes and merge them back into the main
branch when they're ready. Branches let you work on multiple features at the same time without interfering with each other.
Branches are lightweight and easy to create and manage in Git. They allow you to experiment with new ideas, work on different features in parallel, and isolate changes from the main
branch until they're ready to be integrated. Branches are a powerful tool for organizing and managing your project's development workflow.
When you create a new branch, it starts from the latest commit on the current branch.
Remote tracking branches
When your repository is connected to a remote repository (e.g. when you cloned it from GitHub), there will be a special read-only kind of branches created for you whenever you fetch changes from the remote: remote tracking branches.
For example, say your repo is connected to a remote repository named origin
. On that remote repo, there's a branch called cake
. When you run git fetch origin
, Git will download the cake
branch to your local repository and name it origin/cake
. Then, you can create a local branch based on it, like git switch -c cake origin/cake
, or you can merge it into your current branch with git merge origin/cake
.
Examples
Create a new branch called new-feature
and switch into it right away:
git switch -c new-feature
Switch to the main
branch:
git switch main
Merge the other-feature
branch into the current branch:
git merge other-feature
Delete the other-feature
branch:
git branch -d other-feature
Set your current branch to track the remote branch origin/feature
:
# Currently, on a branch named `feature`:
git branch --set-upstream-to=origin/feature
# Shorter version:
git branch -u origin/feature
# Now, you can run `git pull` without specifying
# the remote branch. This will fetch changes
# from `origin/feature` and merge them into
# the `feature` branch:
git pull