Git Fetch and Pull

When other people push to the remote, your local repository does not know about it. You need to bring those changes to your computer. Git has two commands for it: git fetch and git pull.

git fetchgit pull
Downloads the new commits from the remoteDownloads and also merges them into your branch
Does not change your files or your branchChanges your current branch and files
Safe, you can check the changes firstMay cause a merge or a conflict
Same as the first half of pullSame as git fetch + git merge

Prepare an example

Alice and Bob share a server. Bob pushes a new commit, and Alice does not have it yet.

git fetch

Terminal output

$ git fetch
From /home/robin/team/server
043f4e2..c8fddda main -> origin/main
$ git status
On branch main
Your branch is behind 'origin/main' by 1 commit, and can be fast-forwarded.
(use "git pull" to update your local branch)

nothing to commit, working tree clean

After the fetch, Git knows that origin/main is one commit ahead. Our files did not change yet. We can look at what is coming before we take it:

Terminal output

$ git log HEAD..origin/main –oneline
c8fddda (origin/main, origin/HEAD) Bob adds bob.txt
$ git diff main origin/main –stat
bob.txt | 1 +
1 file changed, 1 insertion(+)

If we are happy, we merge it:

Terminal output

$ git merge origin/main
Updating 043f4e2..c8fddda
Fast-forward
bob.txt | 1 +
1 file changed, 1 insertion(+)
create mode 100644 bob.txt
$ git log –oneline
c8fddda (HEAD -> main, origin/main, origin/HEAD) Bob adds bob.txt
043f4e2 First commit

git pull

The same job in one command. Bob pushes one more commit and Alice uses git pull.

Terminal output

$ cd ../bob
$ echo "bob 2" >> bob.txt
$ git commit -q -am "Bob updates bob.txt"
$ git push -q
$ cd ../alice
$ git pull
From /home/robin/team/server
c8fddda..a0edb46 main -> origin/main
Updating c8fddda..a0edb46
Fast-forward
bob.txt | 1 +
1 file changed, 1 insertion(+)

Pull with rebase

By default, git pull makes a merge commit if you also have local commits. With --rebase your commits are replayed on top of the remote ones, and the history stays straight.

git pull --rebase
git config --global pull.rebase true

Fetch and pull other branches and remotes

git fetch --all
git fetch --prune
git pull origin develop

The option --prune removes the local copies of remote branches which are deleted on the server.

Common problems

  • Conflicts: if you changed the same lines as the remote commit, read Git Merge Conflict.
  • Uncommitted changes: commit or stash your work before the pull.
  • “There is no tracking information”: run git branch --set-upstream-to=origin/main or use git pull origin main.
Note: Many developers prefer to run git fetch first, check the changes, and then merge, because it has no surprise. Next: Git Cherry Pick.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.