Git – Make local HEAD the new master
I decided to go back a few commits because the path I followed was wrong. So I checked out
Added cordova to .gitignore commit, and made some modifications. Like illustrated below :
Now when I push the new modifications, an error message shows up :
error: src refspec (detached from aad6423) does not match any.
How can I tell git to discard the previous commits (in purple) and continue with my local HEAD as master ?
5 Solutions collect form web for “Git – Make local HEAD the new master”
Even though you don’t want that old branch anymore, git really doesn’t like rewriting history or discarding changes. Just revert and merge.
git branch new_master # name current detached HEAD git checkout master # switch back to master git revert --no-edit HEAD~4..HEAD # create commits reverting back to where the history split git merge new_master # merge git branch -d new_master # don't need it anymore
Make HEAD your new local
$ git checkout -B master
Force-push your changes:
$ git push -f
Because you have divergence, you’ll need to destroy the remote master and push up the local version. Depending on the security in place, you may not be able to do so. This has other implications as well, depending on who else is doing work based on master. It should be done with extreme caution.
git push origin :master // deletes remote master git push origin master // pushes local master to remote
Another (probably better) approach would be to revert the commits to master and commit the reverts (which themselves are commits). Then cherry-pick the work you’ve done on your local. First, create a new topic branch locally to save your work.
git checkout -b <topic_branch_name> // create new branch to save local work git checkout master git reset --hard HEAD // sync local master to remote HEAD git revert <last commit to master> git revert <second-to-last commit to master> ... git revert <Added cordova to .gitignore commit> git push git cherry-pick <commit hash from topic branch commit(s)>
Since you pushed the changes upstream, the better approach is to revert them with another commit. A commit that will undo the changes.
Removing commits or branches from upstream is bad practice. See this answer for more details.
So, I would do this in a couple steps:
git co -b new_master
to get a nice ref to what you want the new master to be.
git co master ; git co -b old_master
to keep a ref to the old master in case you want to go back or something later ; you can always delete that branch later once you’re sure.
git co master ; git reset --hard new_master
this will reset the HEAD of the branch you’re on (master) to the specified reference (new_master).
git push -f origin
this will do a force-push of your new master branch to the remote. NOTE that this is bad practice if anyone else is using your remote repo as it will potentially break their fetches/pulls.