简体   繁体   中英

git go back to a previous commit before reset hard

I changed some code, then ran

git add .
git commit -m "message1"

But after that, I did

git reset hard
git pull
git push

(The push actually did nothing, of course.)

Now I want to retrieve the state of my files at the point of commit "message1". How can I do that?

git reset hard resets the index (not the working directory) to the state of the branch called hard . So nothing actually changed: you can do a simple git reset to just reset the index. Nothing else has changed anyway.

If you did a git reset --hard then that's a different thing. This will reset the index and uncommitted changes in the working directory to the state of HEAD, ie the last commit of your current branch. Since you made a commit directly before that command, you also lose nothing in case you included all changes of your working directory in that commit. If you did not, then you're out of luck, and those uncommitted changes that never even made it to the index are lost.

The git pull will fetch from the remote and merge any changes into your branch, so this is where something might have actually changed. Since you did a commit locally, there are two cases: You were up to date and nothing was changed; there were changes on the remote and Git created a merge commit. In the latter case, you can revert that using git reset --hard HEAD@{1} . You can also check the reflog using git reflog to see where HEAD was pointing to previously.

As for the git push , it's not obvious that it doesn't do anything. Actually, since you made a commit locally, it should have done something. It should have pushed your commit and an eventual merge commit (as per above) to the remote. In that case, it's not recommended to go back again (with above command) to undo those changes, since you should never remove commits you have already published.

Simply use git reflog . It will display the full history of what you did in your repository.
Once you track the commit that you want to revert to check it out, open a new branch (since you will be in detached HEAD) and continue your work from that point.

Second Thing

Once you adding content to the stash (index) you can always recover it as long as your gc did not run. you can use git fsck to find out the SHA-1 of those dangaling files and recover them using `git cat-file -p' to view the content and copy it to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM