This guide will cover how to create local git branches from existing remote branches, ensuring you can manage and contribute to collaborative projects efficiently.
Understanding branches in Git
Branches in Git are essentially pointers to collections of commits. When you create a branch, you create an independent line of development, which you can switch between, and make code changes in isolation before merging these changes back into your central codebase.
In Git, local branches reside on your own local machine, allowing you to work privately on changes without affecting others. Remote branches, on the other hand, are stored on a server like GitHub, making them accessible to other team members. When you push changes from a local branch, you update the corresponding remote branch, ensuring one central point of truth for your codebase. Conversely, pulling changes from a remote branch updates your local branch with the latest changes from the remote server.
Steps to create a branch from a remote
Fetch the latest changes from remote
Before creating a new branch, ensure your local repository is up to date with the remote repository:
Terminalgit fetch originThis command updates your local copy of the remote branches without merging any changes into your local branches.
Create a local branch from a remote branch
To create a local branch from a remote branch, you first need to know which remote branch you want to base your new local branch on.
To see all of the remote branches you have access to, run the command:
Terminalgit branch -rFrom this list, select the remote branch you wish to make a local copy of then run:
Terminalgit checkout -b <new-branch-name> origin/<remote-branch-name>Replace
<new-branch-name>
with your desired branch name and<remote-branch-name>
with the remote branch you want to base your new branch on.Example:
Terminalgit checkout -b feature-branch origin/mainThis command creates a new branch named
feature-branch
based onorigin/main
and checks it out immediately.
Advanced scenarios
Create a new branch from a specific commit or tag
If you need to base your branch not just on another branch but a specific commit or a tag, use:
Terminalgit checkout -b <new-branch-name> <commit-or-tag>Just like the above steps, this will create a new branch locally that you can make changes to, then add those changes, commit them, and push them up to the remote repository.
For further reading on creating branches from a remote, see the official Git documentation.