271
votes

I forked a GitHub repository. Then I pushed some changes to my fork. Then the original repository merged my changes and some others. Now, I want to merge those changes I'm missing. I tried a simple pull followed by push, but this yield my commits in duplicate. What's the best way to do it?

2

2 Answers

367
votes

You probably have a "remote" for each repository. You need to pull from one remote and push to the other.

If you originally cloned from your fork, that remote will be called "origin". If you haven't added it already, you'll need to add the other repository as another remote:

git remote add <shortname> git://github.com/<ownerName>/repo.git

After that's all set up, you should indeed be able to (github changed default branch from master to main, change as necessary)

git pull <shortname> master
git push origin

Remember, git pull is nothing more than a macro that does git fetch and git merge, in that order. You just need to fetch the list of commits from the other repository and then merge his branch into your tree. Merging should do the right thing with your commits on both branches.

GitHub, in all its perpetual awesomeness, gives you a shortcut, of course. There's a "fast-forward" button on your fork of the repository that you can use to catch your fork up if you're entirely merged into the other side.

77
votes

So the accepted answer above didn't work for me perfectly. Namely, it seemed to lose the link to the original github author when it worked, and then didn't seem to work anymore after that. I think the problem was that the answer left out the / between the remote name and the branch. So it would fetch a branch called master from the remote, but then not be able to do anything with it. Not really sure why.

Here's the way github recommends from their site.

Once you have cloned your forked repo, you do need to add a remote pointing to the original like the previous answer said. They like to call it upstream, but it doesn't matter.

git remote add upstream git://github.com/octocat/Spoon-Knife.git

Then you fetch

git fetch upstream

and you'll see the versions available for merging

From git://github.com/octocat/Spoon-Knife.git
 * [new branch]      gh-pages   -> upstream/gh-pages
 * [new branch]      master     -> upstream/main

Then you just need to choose the branch you want to merge in. Mind you these aren't local branches, they are stored under remotes. But provided you don't have a local branch called upstream/master (which is allowed) you should be fine merging with the line below:

git merge upstream/main

Alternatively you could shortcut the fetch/merge (after the initial fetch at least) with this line:

git pull upstream/main