How to reset HEAD to a certain commit without losing last commit(s) in Git?

My application break. I couldn't find where the bugs are, I know that it started to break at commit( 2201e03 ) that I made.

I'm not sure how to go above that, so I decided to do git reset --hard 619176e to reset my application back to where it used to work.

It's work now. I got the message "HEAD is now at 619176e Fix UI in CD Create and Edit" and my application is also back now. Good !

Then, I develop some more, save, commit, and tried to push again, and I CAN'T. As soon as I make changes, and tried to push, I got a message tell me that I am behind 7 commits, and I should perform and PULL and then PUSH. But I don't want that.

If I do that my application will break again. Thus, even if I am behind 7 commits now. I really don't want to delete those commits yet, but I still want to move forward from 619176e.

What should I do ? If I want to keep those 7 commits AND force git to think that 619176e is my HEAD or MASTER ? and move on from here ?

Should I use git reset HEAD^ ?

Any tip or suggestion will be a huge help for me !!


The basic problem is that you don't want to throw away the faulty commits ons master yet, but that's exactly what git reset --hard 619176e does. You did reset your branch (I assume it's the branch master ), but the remote branch you are pushing to is still pointing to the old (faulty) state, namely 7 commits ahead.

As Dacotah already suggested, this is the perfect use case for a branch. You can create a new branch starting from commit 619176e via git checkout 619176e -b branchname . Then you can introduce new changes, commit and possibly push them.

As soon as you want to re-integrate the work on master with the bugs on it, you will have to decide which parts of the work you want to use, and which you don't. You might also be able to fix the bugs on master . You would commit those changes to master and then you can merge the branches or rebase your new branch on top of master.


In this case I would probably branch my code once I go back a few commits. I'm not sure if this is a best practice but it is a potential fix. The code for a branch is git checkout -b BranchName


What I am about to tell you is very dangerous . If you use:

git push -F

That should force the push to the remote and delete any commits since 619176e. There are a few problems with this. First, if you have other users, they may have the bad commits in their history, and if they push, those bad commits will come back into your repo. Second, if there are other valid commits in the remote, you will lose those.

I'd suggest reverting the bad commits one-by-one, and then if you want squashing them (using an interactive rebase) before pushing the cleaned up repository.

链接地址: http://www.djcxy.com/p/43558.html

上一篇: Git的“主”分支名称不仅仅是一个名字吗?

下一篇: 如何在不丢失Git中的最后一个提交的情况下将HEAD重置为某个提交?