What's the Use of git fetch? - fetch vs pull Comparison

Maybe you, like me, learned to use git pull and didn't even care about the fetch function until you discovered this command.

So what's git fetch used for? The git fetch command can be used to download all commits from the remote repository without affecting your local code.

Basically, git pull first does a git fetch followed by a git merge origin/master.

The function of git fetch is quite simple in practice, but if you're looking for something more detailed, this is the right article!

git fetch

First, we need to understand that in Git there are two versions of the local repository. One version contains your code, with its changes, and the other version mirrors the remote repository, so that it can be used as a contrast to your local version of the code in the case of merge or diff, for example.

To understand this, you can do the following test:

  1. Have one repository in two different directories.
  2. Make a change and commit to one of the directories and then do git push.
  3. In the other repository do a fetch followed by a diff:
    git fetch
    git diff origin/master

You will see the differences between your local code and the remote code (which is actually now on your machine thanks to fetch), with the change just made, without the local code being changed.

This is a safe way to update the mirror of the remote repository in your local repository without merge (yet).

In order to have the remote version on your "desktop", you will still need to merge this commit. And this is done automatically in case of git pull:

git pull

The git pull command exists as a more semantic and simple way to "pull" the code, but in reality it simply runs fetch and then merge. E.g:

git fetch
git merge origin/master

In the above code we have the "origin/master" reference which is nothing more than a reference to the "master" branch copy obtained through git fetch in "origin", which is a shortcut to the remote repository.

Did you find this helpful?

Ricardo Metring

Ricardo Metring

Full stack web developer and co-founder at Criar.io.
I've worked for over 10 years with software development. I'm constantly curious and learning.

Linkedin     Github

Related articles