Integrating Remote Changes with Git Fetch and Pull

Edvin DsouzaEdvin Dsouza
2 min read

Git is a powerful version control system that allows multiple developers to collaborate on the same codebase. An important part of collaborating with Git is integrating changes made by others into your local repository. Git provides two useful commands for this - git fetch and git pull. In this post, I'll walk through a scenario using both to integrate remote changes.

Setting the Scene

Let's say I'm working on a project called project-x with another developer, John. We both cloned the central repository and have local copies on our machines.

John makes some changes on a new branch called feature-a and pushes them to the central repo.

mkdir my-git-repo
cd my-git-repo
echo " feature-a" >> feature-a.java
git init
git add feature-a.java
git commit -m "first commit"
git branch -M master
git remote add origin https://github.com/eddzaa/gitfetch.git
git pull --rebase origin master
git checkout -b feature-a
git add .
git push origin feature-a

I don't have those changes in my local repo yet.

I want to get John's changes so I can test them, but I don't want to merge them into my local master branch yet. This is where git fetch comes in handy.

Fetching Remote Changes

To retrieve John's changes without merging them, I use git fetch:

git fetch

This pulls down John's feature-a branch into my local repository, but doesn't merge it with my branches. I can now check out this branch to view his changes:

git checkout feature-a

I can browse through the code, test it out, etc. When I'm done reviewing, I switch back to my master branch which is unchanged.

Fetching allows me to preview changes before integrating them. Sometimes I may determine I don't want to merge the changes and can provide feedback to John.

Merging Remote Changes

When I'm ready to integrate John's changes into my local master, I use git pull:

git checkout master
git pull origin feature-a

This both fetches the changes from the remote feature-a branch and immediately merges them into my current branch (master).

Now my local master is up-to-date with John's changes. I can push the merged result back up to share with others.

Summary

git fetch and git pull provide useful mechanisms for integrating changes from remote repositories into your local branches.

  • Use git fetch to preview changes without merging

  • Use git pull when you're ready to both fetch remote changes and integrate them in one step

Leveraging both helps you stay in sync with your team and control how/when you integrate changes from others.

0
Subscribe to my newsletter

Read articles from Edvin Dsouza directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Edvin Dsouza
Edvin Dsouza

๐Ÿ‘ฉโ€๐Ÿ’ป DevOps engineer ๐Ÿš€ | Automation enthusiast โš™๏ธ | Infrastructure as code | CI/CD ๐ŸŒŸ Let's build awesome things together!