Pull vs Fetch
Git fetch is used to retrieve commits from a remote repository's branch but it_does not_automatically merge the local branch with the remote tracking branch after those commits have been received.
The above paragraph is a little dense so why don't you reread it one more time.
You provide the exact same information togit fetch
as you do forgit pull
. So you provide the shortname of the remote repository you want to fetch from and then the branch you want to fetch:
$ git fetch origin master
Whengit fetch
is run, the following things happen:
- the commit(s) on the remote branch are copied to the local repository
- the local tracking branch (e.g.
origin/master
) is moved to point to the most recent commit
The important thing to note is that the local branch does not change at all.
You can think ofgit fetch
as half of agit pull
. The other half ofgit pull
is the merging aspect.
One main point when you want to usegit fetch
rather thangit pull
is if your remote branch and your local branch both have changes that neither of the other ones has. In this case, you want to fetch the remote changes to get them in your local branch and then perform a merge manually. Then you can push that new merge commit back to the remote.
Let's take a look at that.
Recap
You can think of thegit pull
command as doing two things:
- fetching remote changes (which adds the commits to the local repository and moves the tracking branch to point to them)
- merging the local branch with the tracking branch
Thegit fetch
command is just the first step. It just retrieves the commits and moves the tracking branch. It_does not_merge the local branch with the tracking branch. The same information provided togit pull
is passed togit fetch
:
- the shorname of the remote repository
- the branch with commits to retrieve
$ git fetch origin master