Fixing the Error: “Remote Contains Work That You Do Not Have Locally”
Today I was contributing an app to a new GitHub repository and I got the error: Updates were rejected because the remote contains work that you do not have locally.
As follows…
error: failed to push some refs to 'https://github.com/thomas-burnside/static-website-1.git'
hint: Updates were rejected because the remote contains work that you do not have locally. This is usually caused by another repository pushing to the same ref. If you want to integrate the remote changes, use 'git pull' before pushing again.
It seems that this error occurs when you try to commit something to a repository but your local branch is “behind” the remote branch.
In my case this was because there was a new repository and it had created a README file that was not in my local machine.
So the way to solve this was to pull from the remote branch and integrate the changes – then start the process of pushing to the repo again.
Step 1 – Pull from the Remote Branch
git pull origin main --rebase
git = starts the git command
pull = (1) fetches changes from a remote repository (2) merges the changes into your local branch
origin = the names that refers to the repository
main = the name of the branch you are pulling changes from
–rebase = rather than merging it pulls the changes from origin/main and then “replays” your local changes on top of the updated branch
Step 2 – Resolve the Merge Conflicts
There may be merge conflicts if you have made changes to the same file.
Or for example in my case where there was 2 README files.
Manually resolve the conflicts by choosing which code to keep from each file.
Step 3 – Add, Rebase and Push
git add <file>
git rebase --continue
git push
add = This “stages” the file (prepares it to be rebased).
<file> = specifies the file to be rebased.
rebase –continue = continues an interrupted rebase process.
push = this essentially sends the committed changes to the remote repository.
Conclusion
Generally it’s best practice to pull from a repository when you begin a coding session.
As we’ve seen this can help avoid the error “Remote Contains Work That You Do Not Have Locally”.
This is true even if it’s a brand new repository (with only a README).
It is also particularly true if you work as part of a team – because it’s best to start off working with your co-workers’ latest code.
For more guides on Git / GitHub please check out the archive here.
Also check out my GitHub profile here for mostly WordPress-related projects.