How to Fetch and Merge Instead of Pull in Git

git

Many professional git users suggest that when working with remote git repositories, one should ‘always fetch and merge instead of pull’. The basic reason for this is that although the quick description of what ‘git pull’ does is ‘fetch the remote branch that your local branch tracks against and merge it into the local branch’, inspecting the source code shows that it actually does a lot more.

How do we actually do this? The syntax of git when working with remotes can be rather confusing.

First, understand that everything git does, happens with files on your machine. Running git branch -a will show you all the branches available to you, including a bunch that will be listed as something like remotes/origin/branchname (for a remote server named origin). These aren’t links to the remote, like you might expect; they’re local copies of the branch as obtained from the remote - which is known to be from a remote because of the remotes/ prefix. That remotes/origin/branchname branch exists on your machine and can be used without connecting to the network at all, though it’ll need to be periodically updated from the network.

In normal operations the only time git will connect to the network is if you run git fetch or git push, including running git fetch via git pull.

This explains the differences in syntax, which might be confusing at first. If we are working with the network, we need to specify which remote we’re working with, as a remote - not as part of a branch. So to update our remote-tracking branches from origin, we do git fetch origin, which will fetch all the origin branches. And if we want to push to origin, we use git push origin branchname, not git push origin/branchname; origin/branchname is a remote-tracking branch on our machine, not a remote machine.

On the other hand, when merging in the fetch & merge pattern, we aren’t interacting with the network at all; we’re just using our local copies of a remote branch. So, the correct command to merge the remote branchname branch into our local working branchname branch is git merge origin/branchname (while having the branchname branch checked out); we don’t need to specify the remote as an argument because we’re not interacting with the network at all.

Hopefully, this helps give a better understanding of how git works. Happy committing!


I'm looking for better ways to build software businesses. Find out if I find something.