When you initialize a new Git project and try to push it to GitHub, you may encounter an error like this:
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'github.com:username/repo.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally.
Why this happens
This problem usually occurs when you:
- Checked “Add a README” or “Add a license” when creating the repository on GitHub. This creates an initial commit on the remote.
- Ran
git initlocally to create a brand-new repository. - Tried to push the local repository to the remote.
At this point, Git considers the local and remote repositories to be two completely independent projects (no shared commit history), so by default it refuses to merge them to prevent mistakes.
The solution
You need to tell Git to allow merging these two unrelated histories.
1. Pull with unrelated histories allowed
Run the following command:
git pull origin main --allow-unrelated-histories
Note: if your main branch is named master, replace main with master.
After running it:
- Git will try to pull the remote changes (such as the LICENSE file) into your local repo.
- An editor may pop up asking you to enter a merge commit message. Usually you can just save and exit (type
:wqin Vim, or pressCtrl+XthenYin Nano). - If there are file conflicts (e.g. both sides have a README.md), you need to resolve them manually and commit.
2. Push to the remote
Once the merge is complete, you can push to the remote normally:
git push -u origin main
Now your local code is successfully uploaded, including the License file that the remote repo was initialized with.