Search code examples
gitgithubsynchronizationrepositorygit-fork

How do I update or sync a forked repository on GitHub?


I forked a project, made changes, and created a pull request which was accepted. New commits were later added to the repository. How do I get those commits into my fork?


Solution

  • In your local clone of your forked repository, you can add the original GitHub repository as a "remote". ("Remotes" are like nicknames for the URLs of repositories - origin is one, for example.) Then you can fetch all the branches from that upstream repository, and rebase your work to continue working on the upstream version. In terms of commands that might look like:

    # Add the remote, call it "upstream":
    
    git remote add upstream https://github.com/whoever/whatever.git
    
    # Fetch all the branches of that remote into remote-tracking branches
    
    git fetch upstream
    
    # Make sure that you're on your main branch:
    
    git checkout main
    
    # Rewrite your main branch so that any commits of yours that
    # aren't already in upstream/main are replayed on top of that
    # other branch:
    
    git rebase upstream/main
    

    If you don't want to rewrite the history of your main branch, (for example because other people may have cloned it) then you should replace the last command with git merge upstream/main. However, for making further pull requests that are as clean as possible, it's probably better to rebase.


    If you've rebased your branch onto upstream/main you may need to force the push in order to push it to your own forked repository on GitHub. You'd do that with:

    git push -f origin main
    

    You only need to use the -f the first time after you've rebased.