我在分支“feature
”。在我完成所有更改之后,我决定在这个分支上完成我的工作。
我首先检查了执行命令所做的所有更改:
git status
上面的git命令打印出以下结果:
On branch feature
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: MyApp/src/Main.java
# modified: MyApp/src/Model.java
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# MyApp/src/other/file1
# MyApp/src/other/file2
如上所述,有两个未跟踪文件file1
和file2
。我根本不想将它们放在我的git存储库中。但由于某种原因,我忘记了这两个文件&amp;通过以下方式直接提交我的更改:
git add .
git commit -m "Some changes"
此时,所有更改包括file1
&amp; file2
已被提交。现在,我怎样才能将自己拯救到排除 file1
&amp; file2
但仍保留其他修改后的更改?
(请不要建议我从磁盘中删除file1
&amp; file2
,我需要在我的本地磁盘上删除它们)
答案 0 :(得分:5)
在您提交并意识到您不想添加这些文件后,您可以这样修复:
git reset HEAD^ --soft
git reset MyApp/src/other/file1 MyApp/src/other/file2
git commit -m "Some changes"
git reset HEAD^ --soft
将撤消上次提交:您的工作目录将恢复到提交之前的状态。感谢--soft
标志,暂存区域将保留原样,因此您可以使用git reset
取消暂存这两个文件并再次提交。
如果您不想将这些文件添加到版本控制中,那么您可能希望忽略它们,方法是将它们添加到项目的.gitignore
文件中:
echo MyApp/src/other/file1 >> .gitignore
echo MyApp/src/other/file2 >> .gitignore
PS:感谢--soft
提示{{1}}。
答案 1 :(得分:1)
你可以
git rm --chached path_to_file
告诉git停止跟踪file1
和file2
。它们将显示为已删除但它们仍将存在于目录中。然后,您将通过git add
添加删除。
您可以选择将文件添加到.gitignore
,因此git将来不会跟踪它们。
然后你用修改修改你的最后一次提交:
git commit --amend
希望它可以帮到你!