Blog

git push rejected (fetch first), then git pull says refusing to merge unrelated histories: pushing an existing project to GitHub

Push a project you started with git init to a GitHub repository created with a README, and the push is rejected (fetch first); git pull then stops with Need to specify how to reconcile divergent branches or refusing to merge unrelated histories. I reproduced it in a real repository and compared three fixes: merging with --allow-unrelated-histories, rebasing, and overwriting with --force-with-lease. Also covers src refspec main does not match any.

Diagram of two rows of commits, one blue and one green, stacked one above the other. Their starting points are apart and not connected, and on the right a yellow line merges the two into a single point.

I wanted to keep some scripts I had been writing locally on GitHub, so I created a new repository in the browser. On the creation page I ticked the option to add a README, then typed git remote add and git push exactly as the instructions on the next page said. Git refused:

 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'https://github.com/<username>/myapp.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally.

Following the hint and running git pull stops with fatal: Need to specify how to reconcile divergent branches. or fatal: refusing to merge unrelated histories instead. None of this means Git is broken. The cause is that GitHub and your local repository now hold two separate histories with no connection between them.

This article first confirms why the errors appear, then compares three ways to combine the two histories into one. The output was captured with Git 2.43.0, using a remote repository created locally (a bare repository) in place of GitHub. The error messages are the same; only the URLs on the To and From lines differ. The steps to reproduce everything are at the end of the article.

What is going on

When you create a repository on GitHub with a README, GitHub immediately makes one commit called Initial commit. Locally, meanwhile, you started from git init and made a commit called First commit. Both of these are root commits with no parent, and they have nothing to do with each other.

GitHub main:  7bf8546 Initial commit         (README.md and .gitignore)
Local main:   909bcc4 First commit           (README.md and app.py)

git push moves the remote branch “forward” to your local commit. If your local history does not contain the remote’s Initial commit, pushing would drop that commit from the branch. Git rejects the push to prevent that.

The difference between (fetch first) and (non-fast-forward) is whether your local repository has already fetched the remote commit. If it has never fetched it, you see fetch first; after a git fetch, you see non-fast-forward. Both mean the same thing: going ahead would make the remote’s commit disappear.

$ git fetch origin
From ../remote
 * [new branch]      main       -> origin/main
$ git push origin main
To ../remote.git
 ! [rejected]        main -> main (non-fast-forward)

Once you have fetched, you can confirm that the two histories have no common ancestor. git merge-base prints the common ancestor of two commits; if there is none, it prints nothing and exits with status 1.

$ git log --oneline --decorate main
909bcc4 (HEAD -> main) First commit
$ git log --oneline --decorate origin/main
7bf8546 (origin/main) Initial commit
$ git merge-base main origin/main; echo "exit $?"
exit 1

Before that: src refspec main does not match any

Sometimes you type git push -u origin main as GitHub suggests and get this error before you even reach the rejection:

$ git push -u origin main
error: src refspec main does not match any
error: failed to push some refs to '../remote.git'

It means there is no local branch called main. GitHub uses main as the default branch of new repositories, but unless init.defaultBranch is set, Git names the first branch master. Git 2.43 shows this hint on git init:

hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change.

If git branch shows * master, rename the local branch to main with git branch -m main and push again. If you type git push -u origin master here instead, the push itself succeeds, but GitHub gets a master branch separate from main. The default branch main still contains only the README while your code ends up on master, so you won’t see your files when you open the repository’s front page. If you created it by mistake, you can delete it with git push origin --delete master.

To avoid this in repositories you create from now on, set the following:

git config --global init.defaultBranch main

With the branch names aligned, pushing again gives you the rejected (fetch first) from the start of this article. This is where the real problem begins.

Two errors that stop git pull

If you follow the hint and run git pull origin main, Git 2.43 fetches successfully but then stops and asks you to specify how to combine the branches.

$ git pull origin main
From ../remote
 * branch            main       -> FETCH_HEAD
 * [new branch]      main       -> origin/main
hint: You have divergent branches and need to specify how to reconcile them.
...
fatal: Need to specify how to reconcile divergent branches.

When both sides have commits the other lacks, git pull has to choose between a merge (creating a commit that joins the two lines) and a rebase (replaying your local commits on top of the other side). Without a setting such as pull.rebase, Git doesn’t pick one for you and stops.

Specify a merge and you get a different error:

$ git pull --no-rebase origin main
From ../remote
 * branch            main       -> FETCH_HEAD
fatal: refusing to merge unrelated histories

By default, Git refuses to merge histories that have no common ancestor. This guards against accidentally merging the repository of a completely different project. When you know, as here, that both are the same project, you just need to allow it explicitly.

Method 1: merge with --allow-unrelated-histories

With --allow-unrelated-histories, Git performs the merge even without a common ancestor. The two histories are combined by creating a single merge commit.

$ git pull --no-rebase --allow-unrelated-histories origin main
From ../remote
 * branch            main       -> FETCH_HEAD
Auto-merging README.md
CONFLICT (add/add): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.

The README.md that GitHub created and your local README.md look like the same file newly added on both sides. That is an add/add conflict. Files that exist on only one side, such as .gitignore, are brought in as they are.

$ git status --short
A  .gitignore
AA README.md
$ cat README.md
# myapp
<<<<<<< HEAD
Description written locally
=======
>>>>>>> 7bf8546d428a8eeedc5af31631f9421f5a89757b

The HEAD side is your local content, and below ======= is GitHub’s. The README on GitHub contains only the auto-generated heading, so keep the local content, delete the marker lines, save the file, and then create the merge commit with git add and git commit.

$ git add README.md
$ git commit --no-edit
$ git log --oneline --graph
*   a17543c Merge branch 'main' of ../remote
|\
| * 7bf8546 Initial commit
* 909bcc4 First commit
$ git push -u origin main
To ../remote.git
   7bf8546..a17543c  main -> main
branch 'main' set up to track 'origin/main'.

This method does not rewrite any of your local commits. The history keeps two roots and gains one merge commit, nothing more.

Method 2: rebase onto GitHub’s commit

git pull --rebase replays your local commits one by one after GitHub’s Initial commit. A rebase works without --allow-unrelated-histories even when there is no common ancestor, and it gives you a single line of history without a merge commit.

$ git pull --rebase origin main
From ../remote
 * branch            main       -> FETCH_HEAD
 * [new branch]      main       -> origin/main
Rebasing (1/1)Auto-merging README.md
CONFLICT (add/add): Merge conflict in README.md
error: could not apply 909bcc4... First commit

The README conflict happens just as in Method 1. Watch the direction of the conflict markers: during a rebase, HEAD points to the commit you are replaying onto, which is the GitHub side. Your local content appears on the >>>>>>> 909bcc4 (First commit) side.

# myapp
<<<<<<< HEAD
=======
Description written locally
>>>>>>> 909bcc4 (First commit)

After fixing and saving the file, continue with git rebase --continue rather than git commit. If you have several local commits, you resolve conflicts commit by commit. If you want to give up midway, git rebase --abort takes you back to where you were before the rebase.

$ git add README.md
$ git rebase --continue
Successfully rebased and updated refs/heads/main.
$ git log --oneline --graph
* 67c00e9 First commit
* 7bf8546 Initial commit
$ git push -u origin main
To ../remote.git
   7bf8546..67c00e9  main -> main

The ID of First commit has changed from 909bcc4 to 67c00e9. A rebase recreates commits even when their content is the same. Since nobody else has this commit yet, that is not a problem here.

Method 3: if you don’t need GitHub’s commit, overwrite with --force-with-lease

If there is nothing you want to keep in the README or .gitignore that GitHub created, you can replace the remote main with your local content. This is only for a freshly created repository that nobody but you is using.

For an overwriting push, use --force-with-lease rather than --force. It is a conditional force push that overwrites the remote branch only if it is still where you last saw it locally, which prevents you from unknowingly wiping out commits someone pushed after you checked. However, if you have never fetched, there is no “last seen” position, so the push is rejected.

$ git push --force-with-lease origin main
To ../remote.git
 ! [rejected]        main -> main (stale info)
error: failed to push some refs to '../remote.git'

Fetch the remote state with git fetch origin, check with git log origin/main that only Initial commit will be lost, and run it again.

$ git fetch origin
$ git log --oneline origin/main
7bf8546 Initial commit
$ git push --force-with-lease origin main
To ../remote.git
 + 7bf8546...909bcc4 main -> main (forced update)

Git shows (forced update), and GitHub’s main now contains only your local First commit. The README and .gitignore on GitHub are gone along with their history, so create and commit them locally if you need them. If branch protection is enabled in the GitHub repository settings, the force push itself is rejected.

Which one to choose

All three put your local files on GitHub’s main, after which ordinary git push and git pull work. What differs is the shape of the history.

Method GitHub’s commit Local commits History shape
Merge with --allow-unrelated-histories Kept Unchanged Two roots plus one merge commit
--rebase Kept Recreated Single line
--force-with-lease Removed Unchanged Single line (local history only)

For a freshly created repository, any of them will do. If you have a long local history and don’t want commit IDs to change, or want to resolve all conflicts in one go, merging is easiest. If you want a single line of history, rebase; if you don’t need GitHub’s auto-generated files, overwrite.

Conversely, if GitHub already has commits from other people, or the same repository is cloned somewhere else, don’t overwrite with --force-with-lease. Avoid rebasing too, since it recreates commits that others already have; combine with a merge instead.

If you lose track of local commits after a force push or git reset, git reflog lets you find where you were. I described the steps in an article on undoing git reset --hard with reflog (in Japanese).

Preventing it next time

This error starts with making a “first commit” both on GitHub and locally. If you make it on only one side, it never happens.

  • If you already have a project locally: when creating the repository on GitHub, untick all the options to add a README, .gitignore or license, so the repository is empty. Your first push goes straight into an empty repository. Create the README and other files locally and commit them.
  • If you are about to start writing: create the repository on GitHub with a README, bring it to your machine with git clone, and work there. A cloned repository starts from the same history as GitHub, so the branch names match as well.

If all you want is one of GitHub’s .gitignore templates, writing .gitignore locally and including it in your first commit saves rework compared with adding it on GitHub after creating the repository. To stop tracking files you have already committed, see Does .gitignore seem to have no effect?.

Reproducing it on your machine

You can recreate the same situation with a local bare repository, even without a GitHub account. Run the following in an empty directory. web stands for the repository created on GitHub with a README, and myapp for your local project.

# GitHub side: create a main with only README and .gitignore
git init --bare -b main remote.git
git clone remote.git web
cd web
git checkout -b main
echo "# myapp" > README.md
echo "node_modules/" > .gitignore
git add . && git commit -m "Initial commit"
git push origin main
cd ..

# Local side: a project created separately with git init
mkdir myapp && cd myapp
git init
printf '# myapp\nDescription written locally\n' > README.md
echo 'print("hello")' > app.py
git add . && git commit -m "First commit"
git remote add origin ../remote.git

git push -u origin main          # src refspec main does not match any if init.defaultBranch is unset
git branch -m main
git push -u origin main          # rejected (fetch first)
git pull --no-rebase origin main # refusing to merge unrelated histories

To try Methods 2 and 3, start again from remote.git. Once a merge has been pushed to a given remote.git, pulling into another copy is just a fast-forward, and the same situation can’t be reproduced. Commit IDs depend on the date and time, so yours won’t match the ones in this article.