Search code examples
gitgit-pull

Why is git pull needed to update a (different) branch (moving branch to latest commit without git pull)?


I would gladly have written a more precise topic for this question, but I cannot express it better at the moment.

Basically, let's say you have a repo where you have several branches, say "master" and "mybranch".

So, let's say you're on master:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Then you do git pull here; new commits are retrieved both for master branch, and the mybranch. Since you are already in branch master, master has its HEAD automatically updated by git to the latest received commit.

Now, let's say you change branch using checkout:

$ git checkout mybranch
Switched to branch 'mybranch'
Your branch is behind 'origin/mybranch' by 2 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

Now this is what puzzles me - in the previous pull, (apparently) all of the latest commits - including those in mybranch - had been retrieved; otherwise my local git would not "know" that my local branch "is behind ... by 2 commits".

So my question is: why would I need to do "git pull" again, having a needless roundtrip to the server - when we already have those new commits for mybranch downloaded? Isn't there a "git update-head" or some command, which would do it locally, without a round-trip to the server?


Solution

  • Your explanation of what happens in the first step is incorrect. When you did git pull from the master branch, you were really doing git pull origin master. This updates the local tracking branch origin/master, then merges this branch into your local master to fast-forward it. It does not affect other branches.

    If you only want to make a single round trip to the Git server, then you could try doing:

    git fetch origin   # update all local tracking branches
    # from e.g. mybranch
    git merge origin/mybranch
    

    Then, if you also wanted to update your local master branch, you would only need to checkout and merge:

    git checkout master
    git merge origin/master
    

    Note that the above two steps happened completely locally, independent of the remote Git server.