What is the difference between 'git pull' and 'git fetch'?

 

Both git pull and git fetch are used to update your local repository with changes from a remote repository, but they have different behaviors:

  1. git pull:

    • git pull is a combination of two commands: git fetch followed by git merge.
    • It fetches the changes from the remote repository and then automatically merges them into your current local branch.
    • This can potentially create merge commits in your local history.
  2. git fetch:

    • git fetch only fetches the changes from the remote repository but does not automatically merge them into your local branch.
    • It updates your remote tracking branches (e.g., origin/master), allowing you to see the latest changes on the remote without affecting your local working branch.
    • You can inspect the changes fetched from the remote before deciding how to integrate them.

Here's an example to illustrate the difference:

Suppose you have a remote repository with a new commit, and your local repository is in sync with it initially:

Remote repository:

css
A - B - C (master) ↑ origin/master

Local repository:

css
A - B - C (master) ↑ origin/master

Now let's see how git fetch and git pull work:

Using git fetch:

bash
git fetch

After git fetch, your local repository is updated with the new commit from the remote, but your working branch (master) is not changed:

css
A - B - C (master) ↑ origin/master

You can choose to inspect the changes, compare branches, or decide how to integrate the fetched changes before merging.

Using git pull:

bash
git pull

After git pull, your local repository is updated, and the fetched changes are automatically merged into your working branch (master):

css
A - B - C - D (master) ↑ origin/master

A new merge commit D is created to integrate the fetched changes into your local branch.

In summary, use git fetch when you want to bring the latest changes from the remote repository without immediately integrating them. Use git pull when you want to both fetch and merge the changes into your local branch. The choice depends on your workflow and whether you want more control over the integration process.

Comments