Git Checkout 将代码恢复到较旧的提交,如何恢复?
我一直在编写一些代码,我使用 git 来管理它们。早些时候,我使用 commit 来保存有效的代码版本。后来我决定重做代码,因为它需要一些新功能并且设计得很糟糕。当我让它工作后,我又做了一次 git commit。执行 git log 后,我发现我不在任何分支上。所以,我做了“git checkout master”。这让我回到了旧代码的版本,git log 现在显示了我最新的提交。这是大量的工作,所以我想知道是否有任何方法可以撤消我所做的事情,并取回我的最新代码。预先感谢您的帮助。
I have been working on some code, which I use git to manage. Earlier, I used commit to save a version of my code that worked. I later decided to redo the code, since it needed some new features and was designed poorly. After I got it working, I did another git commit. After doing git log, I saw I was not on any branch. So, I did "git checkout master". This brought be back to the version of my old code, with git log now showing my latest commit. This was A LOT of work, so I wanted to know if there was any way to undo what I did, and get back my latest code. Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查
git reflog
并找到你的提交。最安全的事情是在“丢失”的提交处创建一个分支,然后使用 gitk 或 git log -p 来检查一切是否正常,
然后可以合并这个新分支,重新建立基础在 git 中,有很多可能搬起石头砸自己的脚,但也有几种方法可以重新连接那只脚(可能是你的手臂)。
如果你没有在 master 上进行任何新的提交,你可以简单地合并有问题的提交,这将被 git 解析为快进合并:
如果你不关心 master 上的任何新提交,并且你只是想要要将 master 分支重置为丢失的提交,请使用 git reset。为了不丢失任何更改,请先将更改存储到工作副本中 (
git stash save
)下次当您发现自己不在任何分支上时,请使用
gitbranch newbranch
或 git checkout -b newbranchCheck the
git reflog
and find your commit.Safest thing is to create a branch at the "lost" commit, then check if everything is dandy using
gitk
orgit log -p
This new branch can then be merged, rebased on top of master, commits of it cherry-picked, etc. There are many possibilities in git to shoot yourself in the foot but also several more ways to re-attach that foot (possibly to your arms).
If you haven't done any new commits on master, you can simply merge the commit in question, which will be resolved as a fast-forward merge by git:
If you don't care about any new commits on master and you simply want to reset master branch to that lost commit, use git reset. To not lose any changes, stash changes to your working copy first (
git stash save
)The next time you discover that you aren't on any branch, use
git branch newbranch
orgit checkout -b newbranch
使用
git reflog
,获取新提交的 sha(或者您可以以HEAD@{1}
等格式引用它)并使用gitcherry-pick< /code>、
git merge
等将提交引入到 master 中。Use
git reflog
, get the sha of your new commit ( or you can reference it in format likeHEAD@{1}
) and usegit cherry-pick
,git merge
etc to bring in the commit to master.