0
0
GitHow-ToBeginner · 3 min read

How to Sync Fork with Upstream in Git: Simple Steps

To sync your fork with the upstream repository, first add the upstream remote using git remote add upstream [URL]. Then fetch the upstream changes with git fetch upstream and merge them into your local branch using git merge upstream/main or rebase with git rebase upstream/main.
📐

Syntax

Here are the main commands to sync your fork with the upstream repository:

  • git remote add upstream [URL]: Adds the original repository as a remote named upstream.
  • git fetch upstream: Downloads the latest changes from the upstream repository.
  • git merge upstream/main: Merges the upstream main branch into your current branch.
  • git rebase upstream/main: Reapplies your commits on top of the upstream main branch for a cleaner history.
bash
git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
git fetch upstream
git checkout main
git merge upstream/main
💻

Example

This example shows how to sync your fork's main branch with the upstream main branch by merging changes.

bash
git remote add upstream https://github.com/octocat/Hello-World.git
# Fetch upstream changes
git fetch upstream
# Switch to your local main branch
git checkout main
# Merge upstream main into your local main
git merge upstream/main
# Push the updated main branch to your fork
git push origin main
Output
From https://github.com/octocat/Hello-World * branch main -> FETCH_HEAD Updating abc1234..def5678 Fast-forward README.md | 2 ++ 1 file changed, 2 insertions(+)
⚠️

Common Pitfalls

Common mistakes when syncing a fork include:

  • Not adding the upstream remote before fetching.
  • Trying to merge or rebase without switching to the correct branch (usually main or master).
  • Conflicts during merge or rebase that need manual resolution.
  • Forgetting to push the updated branch back to your fork on GitHub.

Always check your current branch with git status before merging or rebasing.

bash
git fetch upstream
# Wrong: merging without switching branch
# git merge upstream/main

# Right way:
git checkout main
git merge upstream/main
📊

Quick Reference

Summary of commands to keep your fork up to date:

CommandDescription
git remote add upstream [URL]Add the original repo as upstream remote
git fetch upstreamDownload latest changes from upstream
git checkout mainSwitch to your local main branch
git merge upstream/mainMerge upstream changes into your branch
git rebase upstream/mainRebase your commits on top of upstream
git push origin mainPush updated branch to your fork

Key Takeaways

Add the upstream remote once to link your fork to the original repo.
Fetch upstream changes regularly to keep your fork updated.
Merge or rebase upstream changes into your local branch carefully.
Always push your updated branch back to your fork on GitHub.
Check your current branch before syncing to avoid mistakes.