I am a Developer from Montreal, Canada 🇨🇦. I specialize in React & TypeScript development.
Walkthroughs, tutorials, guides, and tips. This story will teach you how to do something new or how to do something better.
The code in this story is for educational purposes. The readers are solely responsible for whatever they build with it.
对于经常使用 Git 的开发人员来说,操纵历史记录是很常见的。事实上,开发人员经常需要从 Git 历史记录中删除提交。幸运的是,Git 提供了许多命令来使此操作成为可能。
让我们开始吧😎。
在操作 Git 历史记录之前,请使用git status命令确保您的工作目录没有任何更改。
要从远程服务器删除提交,首先,您需要将它们从本地历史记录中删除。
如果要删除的提交位于提交历史记录的顶部,请使用git reset --hard
命令以及HEAD
对象和要删除的提交数。
git reset --hard HEAD~1
此命令将删除最新的提交。
git reset --hard HEAD~3
此命令将删除最新的三个提交。
您还可以使用提交的哈希删除最多特定的提交,如下所示:
git reset --hard <hash>
但是,如果您想删除非连续提交,则需要使用交互式变基。
git reflog
命令查找包含要删除的所有提交的最后提交哈希。git rebase -i <hash>
启动交互式变基。git rebase --continue
结束交互式变基,或者通过中止变基重新开始。要从远程删除提交,您需要使用git push命令将本地更改推送到远程。
git push origin HEAD --force
由于本地历史记录与远程历史记录不同,因此您需要使用force
选项。
正如您所看到的,Git 可以轻松地从远程服务器删除提交。
但是,在使用带有force
选项的git push
命令时需要小心,因为如果不小心,可能会丢失进度。
感谢您的阅读!