How to Set Upstream Branch in Git

Stewart Nguyen Feb 02, 2024
How to Set Upstream Branch in Git

This article will introduce how to set up a relationship between the local branch and the remote branch.

Git calls set upstream to establish this kind of relationship.

The local branch is called the tracking branch, the branch it tracks - the remote branch is called the upstream branch.

The purpose of setting upstream is to make git push and git pull easier.

Imagine you have a long branch name like this, feature/a-long-long-branch-for-feature-A.

Without setting the upstream branch, you need to execute git push with the branch name explicitly.

e.g:

git push origin feature/a-long-long-branch-for-feature-A

It’s shorter, and you can get rid of the branch name you’re working on after setting upstream branch.

Just execute git push, tidy and easy.

To set upstream when the remote branch is not created yet, use the --set-upstream-to option along with the git push command.

git push --set-upstream-to origin <branch_name>

Or its shorter version,

git push -u origin <branch_name>
$ git push -u origin master
Enumerating objects: 17, done.
...
remote: Create a pull request for 'master' on GitHub by visiting:
...
To github.com:username/repo_name.git
 * [new branch]      master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

To set-upstream when the remote branch already exists, use the below command.

git branch --set-upstream-to origin/<branch_name>

Or,

git branch -u origin/<branch_name>

For example,

$ git branch -u origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.

Another benefit of setting upstream is to indicate the unsynced commits between the local and the remote branches.

$ git branch -u origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.
$ touch file.txt
$ git add file.txt && git commit -m 'Add file.txt'
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

To unset upstream, use git branch --unset-upstream; then, git status won’t show the extra information.

$ git branch --unset-upstream
$ git status
On branch master
nothing to commit, working tree clean

Related Article - Git Remote