How to Check out a Remote GIT Branch, which doesn't exist on your local clone?

Backend Pro

Imagine you are working on a git repository shared across multiple team members. Now you and one of your team members are working on a standard feature and must work collaboratively. 


Your peer has created a new branch and made some changes and pushed. Now you have to check out the same branch in your local and continue doing the changes on top of your peer's changes. 


Below are the steps that need to be followed to check out the remote branch. 


To check out a remote Git branch that doesn't exist on your local clone, you can use the following steps:


Step 1: Fetch the remote repository:

Use the command `git fetch origin` to download the latest version of the remote repository, including any new branches.

In the below example, I have created a new branch in https://github.com/ulasalasreenath/TheBackendPro.

To fetch this new branch I executed `git fetch origin` & the result is as follows.

From https://github.com/ulasalasreenath/TheBackendPro
 * [new branch]      dev        -> origin/dev

Step 2: Check the available branches:

Use the command `git branch -a` to see a list of all the available branches, including both local and remote branches. The output of the command is as follows.
  * main
  remotes/origin/HEAD -> origin/main
  remotes/origin/dev
  remotes/origin/main

Step 3: Create a local tracking branch:

Use the command `git checkout -b <branch-name> origin/<branch-name>` to create a local tracking branch for the remote branch. The -b option tells Git to create a new branch, and `origin/<branch-name>` specifies the remote branch to track.

Command: 
  git checkout -b dev origin/dev
Output:
  branch 'dev' set up to track 'origin/dev'.
  Switched to a new branch 'dev'

Step 4: Push the local tracking branch to your remote repository:

After making changes to the local tracking branch, you can push the changes back to the remote repository using the command `git push -u origin <branch-name>`. The -u option sets the local tracking branch to track the remote branch so that future `git push` and `git pull` commands are automatically directed to the correct branch.

Command:
git push -u origin dev
Output:
branch 'dev' set up to track 'origin/dev'.
Everything up-to-date
These steps will allow you to check out a remote Git branch that doesn't exist on your local clone and make changes to the branch. Once you have checked out the remote branch, you can work with it like any other local branch.

Tags

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !