Git Fetch Explained – How to Download from Remote Repos
Git fetching is mainly about getting (downloading) files, commits, and refs from a project’s remote repository to the local repo you are working on.
For instance, suppose you are working on a team project and wish to see your colleagues’ work. In such a case, fetching from the remote repo lets you download and see your teammates’ progress.
Below are the main ways developers fetch from remote directories.
How to Fetch a Remote Repository’s Content
The command above will download <theRemoteRepo>
’s content to your local repository.
How to Fetch from a Specific Branch of a Remote Repository
The command above will download the content of <theSpecificBranch>
only.
Important Stuff to Know about Git Fetching
- Git separates the fetched content from your local work.
- Your local work lives in your local repo’s
./.git/refs/heads/
directory. - The remote work you fetched lives in your local repo’s
./.git/refs/remotes/
directory. - Git automatically maps your fetched content to its remote-tracking branch. The syntax it uses to name the remote-tracking branch is
remote/remote-repo-name/branch-name
. - Use the
git branch -a
command to view your local and remote branches. - Use the
git branch -r
command to view only the remote branches.
How to Switch to a Remote-Tracking Branch
Use git checkout
to switch to the remote-tracking branch (the branch containing your fetched content).
The command above tells Git to switch to remote-repo-name/branch-name
.
After running the git checkout
command, Git will put you in a detached HEAD state.
How to Merge a Fetched Branch with a Local Branch
You can use the git merge
command to merge your fetched content with your local branch.
The code above instructs Git to merge name-of-the-fetched-branch
with the HEAD (current) branch.
Git Fetch vs. Git Pull: What’s the Difference?
git fetch downloads a remote repository to your local repo without merging the differences between the two directories. Instead, Git separates the fetched content from your local work by putting the downloaded data in your local repo’s ./.git/refs/remotes/
directory.
In other words, git fetch
provides a safe way to download a remote repo without altering your local repository. Therefore, you can review the fetched content and decide whether to merge some (or all) of its commits with your local work.
git pull downloads a remote repository to your local repo. Afterward, it automatically uses the git merge
command to merge the differences between the two directories.
Suppose the merge
command encounters conflicts. In that case, Git will auto-start the merge conflict resolution process.
In other words, git pull
provides a quick way to download and merge a remote repo with your local repository.
Here is git pull’s syntax:
The command above will download and merge <theRemoteRepo>
’s content with your local repository.