Search code examples
gitgithubgitlabfetchpull

Why should not use git pull?


I am new in Git and I have used git pull origin <my-branch> in most of the time to get the changes from remote repository.

However, as I get some experience, I have observed that git fetch is preferred more, but reading several topics e.g. What is the difference between 'git pull' and 'git fetch'? and Git: Fetch and merge, don’t pull, now I am confused and need a clarification if there is a valid reason to prefer it except from checking changes before getting them.

The general idea behind this, git pull is git fetch + git merge, nut of course there are several drawbacks, etc.

So, could you please clarify me on:

1. How I should update my local branch from remote?

2. As far as I see, the difference between git pull origin <my-branch> and git pull origin, the latter gets all the branches from origin besides <my-branch>. Is that true? And which one should I prefer?


Solution

  • I use git fetch if I am fetching a new branch that someone else pushed. Let us suppose that I want to look at Mary's latest changes on her branch, featureB.

    I would do:

    git checkout featureB
    git pull origin featureB
    

    That would fetch the latest meta-data for featureB, and merge it into my current copy of featureB.

    But if have never pulled featureB, then I cannot checkout featureB.

    If I have currently checked out my own branch, featureA, then I do not want to perform git pull origin featureB because that would fetch featureB, and then merge it into my featureA branch.

    Therefore I do this:

    git fetch origin featherB
    git checkout featureB
    

    Now I have branch featureB in my local repo.

    Since I now have branch featureB in my local repo, it is now possible to use checkout the next time I want to update it from the remote repo.

    Suppose I had branch featureA checked out, and I want to get the latest version of featureB. I can do this:

    git checkout featureB
    git pull origin featureB