How to Checkout Remote Git Branch

GIt is a popular distributed version control system that allows distributed/remote developers to collaborate effectively. It also allows you to maintain multiple code bases in one place using branches. In this article, we will look at how to checkout remote git branch.


How to Checkout Remote Git Branch

When you create a git project there are at least two copies of your code base – local and remote. The remote one is the master copy on cloud or hosted server while everyone also has a local copy on their laptop/workstation.

When you can create a local branch it exists only on your computer until you push it to the remote git repository. Here is an example of pushing your local branch dev to remote repository. That is when it starts existing as a remote branch.

$ git branch dev #create new branch
$ git checkout dev #switch to new branch
$ touch test.txt #make change
$ git commit -am "new file added" # commit changes
$ git push --set-upstream origin dev #push branch to remote repository

Now your local branch’s copy will also be present at remote master as origin/dev (master/dev)

Also read : How to Run Multiple cURL Requests in Parallel


How to Checkout Remote Git Branch

Here are the steps to checkout remote git branch.


1. Fetch All Remote branches

Run the following command to fetch all remote branches.

git fetch origin

origin is the remote name whose branches we want to checkout

Also read : How to Convert Webpage to PDF in Python


2. List all branches for checkout

Run the following command to list all branches that are available for checkout

git branch -a

This will list all branches (local and remote) available for checkout. The remote branches will be listed with prefix remotes/origin.

Also read : How to Set Upstream Branch in Git


3. Copy a remote branch

You cannot directly make changes to remote branch. You need to create its local copy, make changes to it, and then push the changes to remote branch. Here is the command to checkout remote branch origin/dev.

git checkout -b dev2 origin/dev

The above command will create a new local branch dev2 and copy contents of remote branch origin/dev to it.

Now you can make changes to this branch and push them to origin/dev

$ touch test.txt #make change
$ git commit -am "new file added" # commit changes
$ git push

In the above command, we have not specified where to push changes. git will automatically push changes to origin/dev since it has automatically set local branch dev2 to track remote branch origin/dev when we run git checkout command above.

That’s it. As you can see, there is no specific “git checkout remote branch” command but it is a set of git commands to basically checkout a remote branch.

Also read : Git Stash – Save Local Changes Without Commit

Leave a Reply

Your email address will not be published. Required fields are marked *