How to Fetch Remote Branch in Git
When we collaborate with colleagues, or even when we’re using any open source library, we’ll frequently need to fetch a branch from a remote branch with the help of Git to get the updated work.
The basic procedure to fetch a branch is extremely simple. Still, like other Git operations, it can become quite difficult when other restrictions are applied, and we need to start using one of the many other options available.
This article will highlight the commands that need to be run to fetch the remote branch and the commonly used options.
Fetch Remote Branch in Git
The below mentioned command is used to fetch the remote branch in the local environment:
$ git fetch <remote-repo> <remote-branch>:<local-branch>
$ git checkout <local-branch>
The fetch
command will recover the remote branch that we want with all the objects and references. It will store in a new local branch that we have specified by <local-branch>
as a name.
When we have downloaded everything from the remote repository, we can check it out to review and work with the code.
If we only have one remote repository, we can exclude all of the arguments using git fetch
, which will recover all branches and upgraded files.
Then, run git checkout <branch-name>
, and we know that all remote branches are already on our system.
As mentioned above, the example command will recover all of the code in the branch we’re interested in, but it won’t be harmful to any of the local branches because we know nothing is merged with the fetch command.
Checkout With Track Option in Git
We often want the new local repository to follow the remote repository, which is very supportive for easily pulling
and pushing
the changes to respective repositories.
To execute this, we use the --track
option with the checkout
command, which will check out the branch and track it with the remote branch simultaneously. Below is the command that describes this situation:
$ git checkout --track <remote-branch>
This command will create a local branch of the same name as the remote branch. But if we want to check out the remote branch to a local branch with a unique name, then we have to execute the -b
option with it to create the new local branch, as shown below:
$ git checkout --track -b <local-branch> <remote-branch>
Abdul is a software engineer with an architect background and a passion for full-stack web development with eight years of professional experience in analysis, design, development, implementation, performance tuning, and implementation of business applications.
LinkedIn