我被一个对 git 新手来说似乎很常见的问题所困扰。
我忘记了 .gitignore 一个特定的文件,在提交后将它添加到 .gitignore 没有任何区别。
我找到了 this page on gitready它解释了如何从存储库中删除文件而不将其从工作树中删除(通过使用命令 git rm --cached <file>
,它工作正常,除了如果我然后尝试将其 merge 回另一个分支,工作树中的文件被删除。
在空文件夹上重现的步骤:
git init
touch want.txt
touch wantnot.txt
git add .
git commit -m "Initial"
git checkout -b BranchForIgnore
git rm --cached wantnot.txt
cat > .gitignore
wantnot.txt [Ctrl-D Ctrl-D here to exit cat]
git add .
git commit -m "Ignoring file"
至此,一切正常
git checkout master
git merge BranchForIgnore
此时,我的 wantnot.txt 文件已不在我的 master 中,显然,检查 BranchForIgnore 也无济于事。
怎么办?
最佳答案
I forgot to .gitignore a particular file, and adding it to
.gitignore
after having committed makes no difference.
嗯,当然不是。忽略是关于未跟踪文件(这意味着文件不受版本控制)。
I found a page on gitready which explains how to remove a file from the repository without removing it from the working tree (by using the command
git rm --cached <file>
, which works ok, except that if I then try to merge that back into another branch, the files in the working tree get deleted.
Git 删除文件是因为您可以恢复它,因为它在一个分支中被跟踪。
解决方案是在所有分支中提交“取消跟踪”文件(从版本控制中删除文件),使用git cherry-pick
, 或制作 git rm --cached <file> && git commit -a
在单独的提交分支上,然后在所有分支中 merge 该主题分支(然后从跟踪版本恢复文件)。
关于git - 从忘记 .gitignore 中恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1887049/