我创建了一个新文件(包含相当多的代码和艰苦的工作)并将其提交到我的 git 存储库的主分支。过了一会儿,我意识到我可能应该为该文件创建一个分支。我以为我可以撤销 master 的提交并在分支上再次提交,但我认为我以愚蠢的顺序做了事情。由于某种原因,我首先创建了分支,然后使用 is it possible to revoke commits? 撤销了提交。作为指导。
这基本上是我所做的:
echo "Lots of code and hard work" > newfile.txt
git commit -m "thoughtless commit" newfile.txt
# Oh wait, I should've branched!
git branch thoughtful
git checkout thoughtful
# Hmm, I didn't mean for that last commit to be in master
git checkout master
# get the previous commit's hash
oldhead=$(git log | awk 'BEGIN{commitcount=0; } /^commit/{ if (commitcount++ == 1) { print $2 }; }')
git reset --hard "$oldhead"
git checkout thoughtful
所以现在我显然已经废弃了 master 上的提交(事实上,master 上不再存在“newfile.txt”),但它仍然存在于 master 中>深思熟虑(我猜是reflog)。
是否有人能好心解释一下我在这里做了什么,以及为什么不需要进行深思熟虑的提交?
最佳答案
当您创建分支时thoughtful
,从master
的当前状态开始,其中已经包含提交。从那时起,这两个分支就不再相关了。无论你做什么master
,不会影响thoughtful
。引入该文件的提交仍将是 thoughtful
的一部分不管怎样。
你应该尝试git log thoughtful
和git log master
查看提交的历史记录。上thoughtful
您仍然会看到您尝试从 master 中删除的提交。
更完整的分割如下
假设我们当前处于 master
...
echo "Lots of code and hard work" > newfile.txt
git commit -m "thoughtless commit" newfile.txt
您已在 master
上创建了提交,包含newfile.txt
.
# Oh wait, I should've branched!
git branch thoughtful
您已创建分支 thoughtful
,当前状态为master
,但在其他方面与 master 完全无关。分支的起点是 master
,因为您没有明确指定起点和 master
目前已 checkout 。
git checkout thoughtful
现在您正在使用thoughtful
;你不必checkout
新分支使它们成为现实,此步骤绝对没有效果,因为您执行了以下操作:
# Hmm, I didn't mean for that last commit to be in master
git checkout master
现在您正在使用master
.
# get the previous commit's hash
oldhead=$(git log | awk 'BEGIN{commitcount=0; } /^commit/{ if (commitcount++ == 1) { print $2 }; }')
当您可以直接使用 master~
时,您已经跳过了吨的麻烦才能获得上一次提交。或HEAD~
。 这就是您获取“先前”提交的方式,而不是通过检查 git log
。将来,要撤消上次提交,请使用 git reset --hard HEAD~
.
git reset --hard "$oldhead"
您已更改提交 master
指着。现在它是上面命令发现的任何提交,大概是 newfile.txt
之前的提交被介绍了。使用--hard
导致 Git 也更新工作目录,因此 newfile.txt
消失了;你是否省略了 --hard
, newfile.txt
仍会在目录中,但在 git status
中列为新文件.
git checkout thoughtful
您已返回thoughtful
,其中包含 newfile.txt
,更新您的工作目录并重新引入 newfile.txt
.
关于git - 当您创建 git 分支然后删除以前的提交时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8058045/