What does a git fetch do?

Sivasubramanian S
3 min readFeb 23, 2024

--

Disclaimer : This post is in prolongation to the previous post made in specifc on what happens during a GIT PULL. We talked about FETCH as an overview which we will expand here.

FETCH as the name suggests does fetch an entity from a System. Here in GIT, entity is the commit or branch and System is the Repository from which we are executing the command.

Unlike other commands FETCH has its own speciality. It has the ability to operate irrespective of the branch where we are trying to execute the command. Which means it works to sync commits between Repo(s)(Remote to Local).

Fig : Git Fetch command’s behaviour

what happens under the hood when we do a FETCH?

When the command GIT FETCH is executed, it tries to check the diff between the Remote-Tracking Branches (or Local Directory) and the Remote Repository and then fetches required commits to sync it to the Local Directory.

After this process is complete we can check the Local Directory’s history by running :

                  git log --oneline origin/<branch-name>

The term origin above denotes the Local Directory. Takeaway here is : By adding the term origin before the branch-name allows us to access the Local Directory’s status of the branch.

Fig : Work-around of a FETCH command

Lets analyse the above scenario !

Initial Stage : Describes the commits in the Remote Repo having branch-A, branch-X and branch-U and in the Local and Working Directory, there is this branch-X with two commits — X and Y.

Step 1 : We have checked-out to branch-X in the Working Directory with the commits — X and Y. Here on we execute GIT FETCH command.

Step 2 : The FETCH command checks for the commits which are available in Remote Repository but are not available in the Remote-Tracking Branches (or Local Directory) and fetch those commits into Local Directory.
In our case, the diff commits list would be Commit-Z of Branch-X; and
from Branch-A and Branch-U all the commits are required to be fetched.

Step 3 : Now we could have a look at the commits which have been fetched from Remote Repo are high-lighted as green and others as blue.

Step 4 : Here, when we checkout to the branch-A, all the commits from the Local Directory would be synced to the Working Directory and the history of commits can be verified by checking-out to the branch and running the command log :

             ~/Home/working_dir (<branch-name>) $ git log

Step 5 : We can verify that the commits got synced from Local Directory to the Working directory for branch-A.

Uncover your thoughts :
Why is the commit-Z of branch-X did not show-up in the step 4 ?

--

--

Sivasubramanian S

Updates on my learnings that can help grow as a developer.