DEV Community

Cover image for Difference between Git Fetch and Git Pull

Difference between Git Fetch and Git Pull

Introduction

Git Fetch and Git pull are one of the most commonly used commands, but they can sometimes be misunderstood.

The Git Fetch command alerts the local repository that there are changes in the remote repository without invoking the changes in the local repository. So basically it's saying something is happening in the remote repo but I can't bring it here to the local repository for you automatically.

On the other hand, Git Pull invokes a copy of the changes made in the remote repository into the local repository.

Let's dive in to show how they are used differently.

Git Fetch

Firstly, I will create a simple read.py file with a line "first line of code" on my local machine and push it to the remote repository.

git init
git add file-name
git commit -m "commit message"
git remote add origin "your remote repo url"
git branch -M main
git push -u origin main
Enter fullscreen mode Exit fullscreen mode

Image description
Now we have the file in the remote repository

Image description

Both the local and remote repositories are in sync.

Update the read.py file in the remote repository by adding a "second line of code" in the file.

Image description

The read.py file is updated remotely but what happens in the local repository?

The local repository has 1 commit but the remote repository already has 2 commits.

Now let's do git fetch and see what happens.

Image description

After using git fetch we can see from 029377a which is the initial of the second commit

To merge these changes into our local repository, we need to use

git merge origin/branch-name
Enter fullscreen mode Exit fullscreen mode

Image description

With these, the remote repository files are present in the local repository.

Git Pull

Let's add another line of code in our read.py file in the remote repository.

Image description

There are 3 commits in the remote repo, and 2 commits in the local repository 50b4139

With git pull, let's invoke changes in the local repository

git pull origin branch-name
Enter fullscreen mode Exit fullscreen mode

Image description

With the git pull command, the file was fetched and merged to the local repo from the remote repo, and both repositories have the current files.

Conclusion

This can work as git pull = git fetch + git merge

Top comments (1)

Collapse
 
osalumense profile image
Stephen Akugbe

Hence, the more common use of git pull since we want to both fetch and merge the local repo with the git repo.