如何在Git中还原新创建的文件

如何在Git中还原新创建的文件,git,Git,我在上次提交时添加了一个新的文件uploader.rb。我的意思是这个文件在以前的任何提交中都不存在。但我不想提交这个文件。在此文件提交中,已提交两个旧文件。我试过使用git reset uploader.rb。但这是行不通的。有没有办法让我只重设这个文件?提前感谢。首先,您需要将当前分支重置为“撤消”上一次提交,这将使uploader.rb和其他两个文件处于最新提交之前的状态: git reset HEAD^ 然后重新提交要保留在原始提交中的两个文件: git add otherfile1

我在上次提交时添加了一个新的文件uploader.rb。我的意思是这个文件在以前的任何提交中都不存在。但我不想提交这个文件。在此文件提交中,已提交两个旧文件。我试过使用
git reset uploader.rb
。但这是行不通的。有没有办法让我只重设这个文件?提前感谢。

首先,您需要将当前分支重置为“撤消”上一次提交,这将使
uploader.rb
和其他两个文件处于最新提交之前的状态:

git reset HEAD^
然后重新提交要保留在原始提交中的两个文件:

git add otherfile1 otherfile2
git commit

好吧,假设你提交了
好的
坏的
,第二个不应该提交。首先,假设这是最后一次提交。然后你可以:

git reset HEAD^     # Go back one commit, undo
git add good        # Set up to commit just the good stuff
git commit          # Redo the botched commit
如果这是一些提交,您可以重写历史来修复它。但是要小心

git tag OldPlace        # Mark for case something explodes

gitk --all              # Show history, find the commit *before* the mess
git rebase -i SHA-FROM_ABOVE
                        # Mark the relevant commit for editing, exit the editor
                        # When you get the prompt back...
git add good
git commit              # redo...
git rebase --continue   # Rip through the other changes

git tag -d OldPlace     # Get rid of the mark, if everything is OK

假设您没有推动修改,我想您可以尝试删除该文件

git rm uploader.rb
git commit -m "deleted uploader.rb"
然后执行交互式重基以清除提交历史记录

git rebase -i HEAD~2
它将向您显示如下内容,以及最后两次提交:

pick f7f3f6d deleted uploader.rb
pick 310154e message of the previous commit
将“拾取”替换为“挤压”,然后保存

squash f7f3f6d deleted uploader.rb
pick 310154e message of the previous commit
它将合并您的两个提交。一旦删除,历史就会消失

否则,如果已经推送修改,则修改提交历史记录。您必须深入研究文件并提交修改。

检查答案