Git Fetch: Updating Your Local Repository Without Merging
git fetch
is used to download changes from a remote repository without merging them. It allows you to check for updates before applying them, making it safer than git pull
, which automatically merges changes.
1. Fetching Updates from a Remote Repository
To fetch changes from the remote repository (default: origin
):
git fetch
🔹 This updates your local remote-tracking branches (e.g., origin/main
) but does not modify your working directory.
To fetch changes from a specific branch:
git fetch origin feature-branch
2. Checking Fetched Changes
After fetching, check for new commits with:
git log HEAD..origin/main --oneline
🔹 This shows commits in origin/main
that are not yet in your local branch.
To see the differences between your branch and the fetched remote branch:
git diff main origin/main
3. Applying Fetched Changes
Once you have fetched updates, you can choose how to apply them:
3.1 Merge Changes (Similar to git pull
)
git merge origin/main
🔹 This merges the remote branch into your current branch.
3.2 Rebase Changes (For a Clean History)
git rebase origin/main
🔹 This applies remote changes on top of your local changes, keeping a linear commit history.
4. Fetching and Pruning Deleted Branches
If a branch has been deleted on the remote repository, you can remove the stale reference locally:
git fetch --prune
🔹 This removes deleted remote branches from git branch -r
.
To prune a specific branch:
git fetch origin --prune feature-branch
5. Fetching All Remote Branches
To fetch updates from all remote branches:
git fetch --all
🔹 Useful when working with multiple remotes.
6. Checking Remote Branches After Fetching
To list all remote branches:
git branch -r
To switch to a fetched remote branch:
git checkout -b new-branch origin/new-branch
Conclusion
Action | Command |
---|---|
Fetch updates | git fetch |
Fetch from a specific branch | git fetch origin feature-branch |
View new commits after fetching | git log HEAD..origin/main --oneline |
Merge fetched changes | git merge origin/main |
Rebase fetched changes | git rebase origin/main |
Remove deleted remote branches | git fetch --prune |
Fetch all remotes | git fetch --all |
🔹 Use git fetch
to stay updated without modifying your work! Need more details? 🚀