I am trying to push my local commits to a remote repository, but I keep getting an error stating that the push was rejected because the remote contains work that I do not have locally. This usually happens when I've made changes on another machine or a teammate has merged a pull request. What is the safest way to integrate these remote changes into my local branch without causing major merge conflicts or losing my recent work?
3 answers
This error occurs because your local branch is behind its remote counterpart, and Git prevents you from overwriting history. The standard solution is to perform a git pull to fetch and merge the remote changes into your local branch. However, to keep a clean, linear project history, many developers prefer using git pull --rebase. This command takes your local commits, temporarily sets them aside, applies the remote commits, and then re-applies your commits on top of the new head. If there are conflicts, Git will pause and ask you to resolve them manually before finishing the rebase process. Once the rebase is complete, you will be able to push your code successfully.
Are you working on a shared branch where others are pushing frequently, or is this a solo project where you might have edited a file directly through the GitHub web interface?
You should run git fetch origin followed by git merge origin/master. This updates your local tracking branches and merges the work before you attempt to push again.
I agree with Steven. Explicitly fetching and merging gives you more control over the process than a blind pull. It allows you to see exactly what changed on the remote before you integrate it.
Charles, that's exactly what happened. I updated the README.md file directly on the GitHub website and forgot to pull those changes to my local machine before I started my new feature. I was worried that a simple pull might create a messy merge commit. Would you suggest using the rebase method Sandra mentioned, or is there a way to just "force" my local version to be the master version if I know for a fact the web edit was insignificant?