Fetch Remote with git fetch
In this step, we will learn how to fetch changes from a remote Git repository. Imagine you are collaborating with others, and they have made changes to the project. git fetch
is the command you use to download those changes to your local machine without merging them into your current work.
First, let's simulate having a remote repository. We'll create a simple one locally for demonstration purposes.
cd ~/project
mkdir remote-repo
cd remote-repo
git init --bare
This creates a "bare" repository, which is typically used as a central remote repository. Now, let's go back to our my-time-machine
repository and add this as a remote.
cd ~/project/my-time-machine
git remote add origin ../remote-repo
We've added a remote named origin
pointing to our simulated remote repository. Now, let's make a change in the remote repository and then fetch it.
cd ~/project/remote-repo
echo "This is a remote change." > remote_file.txt
git add remote_file.txt
git commit -m "Add remote file"
Now, back in our my-time-machine
repository, let's fetch the changes from the remote.
cd ~/project/my-time-machine
git fetch origin
You should see output indicating that Git has downloaded the changes from the remote repository. Something like this:
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 2 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (2/2), 258 bytes | 258.00 KiB | elapsed 0.00s.
From ../remote-repo
* [new branch] master -> origin/master
The git fetch
command downloads the commits, files, and references from the remote repository into your local repository. However, it does not automatically merge these changes into your current working branch. This allows you to inspect the changes before integrating them.
Think of git fetch
as getting the latest updates from a news feed. You see the headlines and summaries, but you haven't read the full articles yet. You can decide which articles (changes) you want to read (merge) later.