Search code examples
gitgithubgit-push

Why can't I just do git push after creating remote repo?


Creating a new GitHub repo is super simple. On the command line:

git init
git add .
git commit -m "Initial commit"

Then you go into GitHub and create your repo, which creates a Git URL for it, say, https://github.com/<myuser>/<myRepo>.git, etc. Then you go back to the command line:

git remote add origin https://github.com/<myuser>/<myRepo>.git
git push -u origin master

And voila -- you have a git repo! However something isn't sitting right with me. After you issue this command:

git remote add origin https://github.com/<myuser>/<myRepo>.git

Then my understanding is that your local repo is "connected to" (being tracked againt) the remote master branch of your remote GitHub repo (again: https://github.com/<myuser>/<myRepo>.git).

So why do I then need -u origin master on the next command? That is, why do I need my last command above to be git push -u origin master, and not just git push?! The local repo is "connected" to the remote master, right?! So why can't I just git push it?


Solution

  • Running git remote add... just labels a remote URL. It doesn't "connect" anything. In particular, it doesn't make any association between your local branches and the remote branches. This only happens on a per-branch basis (that is, it makes no sense to say that your repository is connected to another repository; you can only talk about tracking in terms of individual branches). The tracking relationship is only set up when you git checkout a local branch corresponding to a remote branch, or when you explicitly set the tracking information with -u when running git push.

    Consider a situation in which you have multiple remotes, e.g. you have run something like:

    git remote add upstream ...
    git remote add origin ...
    git remote add anotherdeveloper ...
    

    If you have a local branch named master, to which of those remotes should git push send your changes unless you tell git explicitly?