How to Set Upstream in Git Push

Azhar Bashir Khan Feb 02, 2024
How to Set Upstream in Git Push

This tutorial will teach us to set up upstream branches in Git while doing a git push.

Upstream branches are the branches on the remote repository that are tracked by a local remote branch in the local repository. These local remote branches are also called remote-tracking branches.

When we create a branch in Git, we will have to set up an upstream branch to work properly. We will now illustrate this with an example.

Using git Push to Set Up Upstream Branch in Git

Suppose we have created a branch viz. feature1 for some feature development below.

$ git checkout -b feature1
Switched to a new branch 'feature1'

We will now check the tracking branches using the git branch command with the -vv option.

$ git branch -vv
* feature1  741a786 Initial commit
 main  741a786 [origin/main] Initial commit

We can see that the main branch has a tracking branch and an upstream branch associated with it. In comparison, the branch feature1 we just created has no tracking branch and has no upstream branch associated with it.

Thus, now we will set up the upstream branch using the git push command with the --set-upstream option.

$ git push --set-upstream origin feature1
Total 0 (delta 0), reused 0 (delta 0)
 * [new branch]      feature1 -> feature1
Branch 'feature1' set up to track remote branch 'feature1' from 'origin'.

We will check the tracking branches of both the branches again, as follows.

$ git branch -vv
* feature1  741a786 [origin/branch] Initial commit
main  741a786 [origin/main] Initial commit

We can see that both the branches viz. feature1 and main have upstream branches set.

The setting of upstream branches in Git is convenient because when one does a git fetch, new commits from the remote repository can be fetched, and then one can choose to merge those changes.

Another use is that when one does a git pull (to get remote repository changes) or git push (to push changes to the remote repository), one no longer needs to provide the target branch in those commands.

For example, one can execute as follows to push the new changes to the remote repository.

$ git push

Explore the following site for more information on the git push command and the available options - git push.

Related Article - Git Push

Related Article - Git Branch

Related Article - Git Upstream