Whenever I push my newly created local repository to a remote repo, I am prompted with this message.
Enough is enough, I have searched about it and I am going to write about it.
What is Upstream?
Upstream is the name of remote branch to which our local branch is synced. Every local branch has exactly one upstream set. Say we have a
local branch A and its upstream is set to origin/B, then every push will push the changes to origin/B etc. git branch -vv can be
used to print the remote tracking branch.
Here master branch is tracking origin/master.
Why Upstream?
Setting upstream has effect on many commands e.g. push, pull, merge. When these commands are used without any conditional arguments,
remote branch information is retrieved from its upstream. Say, I have created a new repository and added its origin
Everything is fine till now. Let’s use pull to fetch data from remote
See, git pull need to know which remote branch it needs to pull data from. As we haven’t set any upstream yet, git provides us two options.
Either use git pull <remote> <branch>, pass everything explicitly to pull command.
OR
Set it’s upstream to
next time you don’t need to pass everything. Just use git fetch/status/merge/pull whatever
you want.
Let’s chose the first option and see the result.
It syncs out current branch with orgin/master but still we haven’t set its upstream we need to write the whole command again if we want to
push or fetch. e.g.
Now let’s try all this with setting upstream first.
Upstream for newly created branch
When a new branch is created using (git branch branch-name), it is created locally without having any link to remote. Pushing it to
remote will do this
Create a new branch in remote repo
Add its reference to remote tracking branches locally.
Despite of all this, git does not set any upstream for this local branch. In this case, you can use
I have done the same in above example.
Upstream for cloned repository
Let’s end it with this observation, “whenever I clone a repository, I don’t need to set its upstream. Everything just works fine.”. This is
because when I clone a remote repository, git checkouts into master branch and sets master branch to track origin/master.
Push with -u
Another thing that is mentioned when a new repo is created on Github or any other site
In either case, they tell you to use push with -u switch.
Push -u does one special thing, apart from pushing data to remote, it also sets the upstream for current branch.
Hopefully, next time you will know what’s going on while setting upstream and it will not bother you or me anymore.