How to Set the Upstream Origin Branch in Git


By squashlabs, Last Updated: October 27, 2023

How to Set the Upstream Origin Branch in Git

To set the upstream origin branch in Git, follow the steps below:

Step 1: Check the Remote Repository

First, check which remote repository is currently configured for your local repository. You can use the following command to view the remote repositories:

git remote -v

This command will display the remote repository URLs along with their corresponding names.

Step 2: Add the Upstream Remote

If the upstream remote doesn’t exist, you need to add it. The upstream remote represents the original repository from which your local repository was cloned. To add the upstream remote, use the following command:

git remote add upstream <upstream_repository_url>

Replace <upstream_repository_url> with the URL of the upstream repository.

Step 3: Fetch the Upstream Branches

After adding the upstream remote, you need to fetch the branches from the upstream repository. Use the following command to fetch the upstream branches:

git fetch upstream

This command will retrieve all the branches from the upstream repository and store them locally in your repository.

A better way to build and deploy Web Apps

  Cloud Dev Environments
  Test/QA enviroments

One-click preview environments for each branch of code.

Step 4: Set Upstream Branch

To set the upstream branch for a specific local branch, use the following command:

git branch --set-upstream-to=upstream/<upstream_branch> <local_branch>

Replace <upstream_branch> with the name of the branch in the upstream repository that you want to set as the upstream branch. Replace <local_branch> with the name of your local branch.

Step 5: Verify the Upstream Configuration

To verify that the upstream configuration has been set correctly, use the following command:

git branch -vv

This command will display a list of all the local branches along with their upstream branches. You should see the upstream branch listed next to your local branch.

Best Practices

Here are some best practices to keep in mind when setting the upstream origin branch in Git:

– Always check the remote repository configuration before adding the upstream remote. This will help you avoid adding duplicate remotes.

– It is recommended to fetch the upstream branches regularly to keep your local repository up to date with the latest changes from the upstream repository.

– Double-check the upstream branch name before setting it as the upstream branch for your local branch. Using the wrong branch name may lead to incorrect tracking.

– When working with multiple branches, it’s a good practice to set the upstream branch for each local branch to ensure proper synchronization with the upstream repository.

– Make sure to verify the upstream configuration after setting it to confirm that it has been set correctly.

More Articles from the Git Tutorial: From Basics to Advanced Concepts series: