A Detailed Guide to Git Cloning and Security Updates

"Fetch" is an operation that downloads updates from a remote repository without automatically merging them. Compared to "pull," "fetch" is safer and more controllable, allowing you to review the updates first before deciding whether to merge them. Understanding how to use "fetch" is crucial for team collaboration.

1. Understanding the Basic Concepts

(1) What Is Acquisition?

"Fetch" is an operation that downloads updates from a remote repository but does not modify the current branch:

100%
graph TB
    A[Remote Repository<br/>Remote] -->|git fetch| B[Remote Branch Replica<br/>origin/main]
    B --> C{View Updates}
    C -->|Satisfied| D[git merge]
    C -->|Not satisfied| E[Leave it as is]
    D --> F[Current Branch<br/>main]
    
    style A fill:#d4edda
    style B fill:#fff3cd
    style F fill:#c3e6cb

(2) fetch vs pull

Feature fetch pull
Download Update
Auto-merge
Change the current branch
Safety High Medium
Controllability High Low

(3) The Purpose of Retrieval


2. Basic Retrieval Operations

(1) Get all updates

▶ Example: Get Updates

BASH
# Get updates from all remote repositories
git fetch

# Output:
# remote: Enumerating objects: 8, done.
# remote: Counting objects: 100% (8/8), done.
# remote: Compressing objects: 100% (5/5), done.
# remote: Total 5 (delta 3), reused 0 (delta 0), pack-reused 0
# Unpacking objects: 100% (5/5), 1.23 KiB | 1.23 MiB/s, done.
# From https://github.com/user/repo
#    a1b2c3d..d4e5f6g  main        -> origin/main
#  * [new branch]      feature     -> origin/feature
#  * [new tag]         v1.0.0      -> v1.0.0

(2) Retrieve a specific remote

▶ Example: Retrieving a specific remote

BASH
# GetoriginUpdates
git fetch origin

# GetupstreamUpdates
git fetch upstream

# Get all remote repositories
git fetch --all

# Output:
# Fetching origin
# Fetching upstream
# Fetching backup

(3) Retrieve a specific branch

▶ Example: Retrieving a Specific Branch

BASH
# Get a Specific Branch
git fetch origin main

# Retrieve Multiple Branches
git fetch origin main develop

# Fetch a remote branch with a different name locally
git fetch origin main:local-main

# Retrieve and Create a Local Branch
git fetch origin feature:feature

3. View the updates you've received

(1) View remote branches

▶ Example: Viewing a remote branch

BASH
# Get Updates
git fetch origin

# View Remote Branches
git branch -r

# Output:
#   origin/HEAD -> origin/main
#   origin/main
#   origin/develop
#   origin/feature

# View All Branches
git branch -a

# Output:
# * main
#   develop
#   remotes/origin/HEAD -> origin/main
#   remotes/origin/main
#   remotes/origin/develop
#   remotes/origin/feature

(2) View the contents of the remote update

▶ Example: View update details

BASH
# View the latest commit on a remote branch
git log origin/main

# Output:
# commit d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2
# Author: Zhang San <zhangsan@example.com>
# Date:   Mon Jan 1 10:00:00 2026 +0800
#
#     feat: Add a New Feature

# View new commits on the remote repository(Not available locally)
git log main..origin/main

# Output:
# d4e5f6g (origin/main) feat: Add a New Feature
# h7i8j9k fix: FixBug

# View commits that exist locally but not remotely
git log origin/main..main

# View Bidirectional Differences
git log main...origin/main

(3) Comparing Local and Remote

▶ Example: Comparing Differences

BASH
# Compare the differences between local and remote
git diff main origin/main

# View Difference Statistics
git diff --stat main origin/main

# Output:
#  src/auth.js  | 10 ++++++++++
#  src/user.js  |  5 ++---
#  2 files changed, 12 insertions(+), 3 deletions(-)

# View the list of modified files
git diff --name-only main origin/main

# Output:
# src/auth.js
# src/user.js

# View detailed file status
git diff --name-status main origin/main

# Output:
# M  src/auth.js
# M  src/user.js

4. Merge the Retrieved Updates

(1) Merge remote updates

▶ Example: Merge Update

BASH
# Get Updates
git fetch origin

# View Updates
git log main..origin/main

# Merge Remote Updates
git merge origin/main

# Output:
# Updating a1b2c3d..d4e5f6g
# Fast-forward
#  src/auth.js | 10 ++++++++++
#  1 file changed, 10 insertions(+)

(2) Merging Using Rebase

▶ Example: Rebase Update

BASH
# Get Updates
git fetch origin

# UsagerebaseMerge
git rebase origin/main

# Output:
# First, rewinding head to replay your work on top of it...
# Fast-forwarded main to d4e5f6g.

# If there is a conflict
# CONFLICT (content): Merge conflict in file.js
# After Resolving the Conflict
git add file.js
git rebase --continue

(3) Selective Merging

▶ Example: Cherry-picking a specific commit

BASH
# Get Updates
git fetch origin

# View new commits on the remote repository
git log main..origin/main --oneline

# Output:
# d4e5f6g feat: Add FeatureC
# h7i8j9k fix: FixBug
# k9l0m1n feat: Add FeatureB

# Merge only a specific commit
git cherry-pick h7i8j9k

# Or merge multiple commits
git cherry-pick k9l0m1n d4e5f6g

5. Retrieve Tags

(1) Retrieve remote tags

▶ Example: Retrieving a tag

BASH
# Get Updates(Including tags)
git fetch origin

# Output:
#  * [new tag]         v1.0.0      -> v1.0.0
#  * [new tag]         v1.1.0      -> v1.1.0

# View All Tags
git tag

# Output:
# v1.0.0
# v1.1.0

# View tag details
git show v1.0.0

(2) Retrieve a specific tag

▶ Example: Retrieving a Specific Tag

BASH
# Get a specific tag
git fetch origin refs/tags/v1.0.0:refs/tags/v1.0.0

# Get all tags
git fetch --tags

# Delete Local Tags(Remotely Deleted)
git fetch --prune-tags

# Or
git fetch -p --prune-tags

6. Detailed Explanation of Options

(1) Common Retrieval Options

Option Description Use Case
--all Fetch all remotes Update all remotes
-p Clean up stale references Remote branch deleted
--tags Get All Tags Sync Tags
--prune-tags Clean up expired tags Tags have been deleted
--dry-run Simulate retrieval Preview retrieved content
--verbose Detailed Output Debug

▶ Example: Using the "Get" option

BASH
# Clean up expired remote branch references
git fetch -p

# Output:
# From https://github.com/user/repo
#  x [deleted]         (none)     -> origin/old-feature

# Delete Expired Tags
git fetch --prune-tags

# Simulated Acquisition
git fetch --dry-run

# Detailed Output
git fetch --verbose

# Gain Insight(Shallow Cloning)
git fetch --depth=1

# Get a single branch
git fetch --single-branch

(2) Clean up expired references

▶ Example: Cleaning Up Remote References

BASH
# View the branches that need to be cleaned up
git remote prune origin --dry-run

# Output:
# * origin/deleted-branch would be pruned

# Perform Cleanup
git remote prune origin

# Or usefetch -p
git fetch -p

# Output:
# From https://github.com/user/repo
#  x [deleted]         (none)     -> origin/deleted-branch

7. The fetch workflow

(1) Security Update Workflow

100%
sequenceDiagram
    participant Developer
    participant Local Warehouse
    participant Remote Branch
    participant Remote Repository
    
    Developer->>Remote Repository: git fetch origin
    Remote Repository->>Remote Branch: Updateorigin/main
    Developer->>Remote Branch: git log main..origin/main
    Developer->>Remote Branch: git diff main origin/main
    Developer->>Local Warehouse: git merge origin/main

(2) Real-world application scenarios

▶ Example: fetch workflow

BASH
# Scene1:Check for Updates Before Starting Work
git fetch origin
git log main..origin/main --oneline

# Output:
# d4e5f6g feat: New Features
# h7i8j9k fix: BugFix

# View Specific Changes
git diff main origin/main

# Decide whether to merge
git merge origin/main

# Scene2:There is unsubmitted work,Get it first, then decide
git fetch origin
git status

# Output:
# On branch main
# Your branch is behind 'origin/main' by 2 commits.

# View Updates
git log HEAD..origin/main

# Save the current work
git stash

# Merge Updates
git merge origin/main

# Return to Work
git stash pop

# Scene3:ForkWorkflow
git fetch upstream
git log main..upstream/main
git merge upstream/main
git push origin main

(3) Periodic synchronization script

▶ Example: Automatic Synchronization Script

BASH
#!/bin/bash
# sync.sh - Regularly Synchronize Remote Updates

# Get all remote updates
git fetch --all

# Check the status of each branch
for branch in $(git branch --format='%(refname:short)'); do
    upstream=$(git rev-parse --abbrev-ref $branch@{upstream} 2>/dev/null)
    if [ -n "$upstream" ]; then
        behind=$(git rev-list --count $branch..$upstream 2>/dev/null)
        ahead=$(git rev-list --count $upstream..$branch 2>/dev/null)
        if [ "$behind" -gt 0 ] || [ "$ahead" -gt 0 ]; then
            echo "$branch: behind $behind, ahead $ahead"
        fi
    fi
done

# Ask if it's synced
read -p "Sync main branch? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    git checkout main
    git merge origin/main
fi

❓ FAQ

Q Should I use fetch or pull?
A We recommend using fetch. fetch is safer because it allows you to review the changes before deciding whether to merge them. pull merges automatically, which may result in unexpected conflicts. It’s better to get into the habit of fetching before merging.
Q Does fetch modify the local code?
A No. fetch only downloads updates to remote branch references (such as origin/main); it does not modify the current branch or the working directory. You must manually merge or rebase to modify the local code.
Q How can I see what Fetch has downloaded?
A Use git log HEAD..origin/main to view new commits on the remote, git diff HEAD origin/main to view differences, and git diff --stat HEAD origin/main to view statistics.
Q How do I merge after a fetch?
A Use git merge origin/main to merge remote updates, or use git rebase origin/main to perform a rebase merge. We recommend using rebase to maintain a linear history.
Q How do I clean up references to deleted remote branches?
A Use git fetch -p or git remote prune origin to clean up expired remote branch references on your local machine. This does not affect the remote repository; it only cleans up the local references.

📖 Summary


📝 Exercises

  1. Basic Exercise: Create a new commit in the remote repository, use fetch locally to retrieve the updates, view the new commit and the differences on the remote, and then manually merge them.

  2. Advanced Exercise: Simulate a fork workflow: Add two remotes, origin and upstream; fetch updates from upstream; review the differences; selectively merge them into your local repository; then push to origin.

  3. Challenge: Write a script that periodically fetches all remote repositories, checks the differences between each branch and the remote, generates a synchronization report, and indicates which branches need to be synchronized.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏