Fetch Remote with git fetch
In this step, we'll learn how to fetch changes from a remote repository. Imagine you're working on a project with others, and they've made some updates. You need to get those updates to your local machine. The git fetch
command is how you do this. It downloads the latest changes from a remote repository but doesn't merge them into your current branch.
First, let's simulate having a remote repository. We'll create a bare repository and then add it as a remote to our existing my-time-machine
repository.
cd ~/project
mkdir remote-repo.git
cd remote-repo.git
git init --bare
This creates a bare Git repository, which is typically used as a central repository that developers push and pull from.
Now, let's go back to our my-time-machine
repository and add this bare repository as a remote.
cd ~/project/my-time-machine
git remote add origin ~/project/remote-repo.git
We've named our remote origin
, which is a common convention. Now, let's verify that the remote was added correctly.
git remote -v
You should see output similar to this, showing the fetch and push URLs for the origin
remote:
origin /home/labex/project/remote-repo.git (fetch)
origin /home/labex/project/remote-repo.git (push)
Now, let's simulate a change in the remote repository. Since it's a bare repository, we can't directly make commits in it. Instead, we'll simulate a change by creating a new file in the bare repository's directory.
cd ~/project/remote-repo.git
echo "This is a remote change" > remote_file.txt
Now, go back to your my-time-machine
repository.
cd ~/project/my-time-machine
At this point, your local repository doesn't know about the remote_file.txt
that was added to the simulated remote. This is where git fetch
comes in.
Run the git fetch
command:
git fetch origin
You might not see much output, or you might see something indicating that new objects were received.
What git fetch origin
did was connect to the origin
remote and download any new commits and objects that are not in your local repository. However, it did not merge these changes into your current branch (master
). The changes are now available in your local repository, but they are stored in a special branch that tracks the remote, typically named origin/master
.
This is a key difference between git fetch
and git pull
. git pull
is essentially git fetch
followed by a merge. By using git fetch
first, you can see what changes are available on the remote before deciding to integrate them into your work. This gives you more control and helps prevent unexpected conflicts.
In the next step, we'll see how to compare your local branch with the fetched remote branch to understand what changes were downloaded.