git - 从忘记 .gitignore 中恢复

标签 git

我被一个对 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/

相关文章:

git - 为什么在 git reset (--mixed) 之前显式调用 git reset --soft

git - 一个提交对象怎么可能有 2 个作者?

git - 为什么我不能使用 gitosis 添加新的存储库?

git - 删除推送提交但保留本地更改

git - 如何比较两个 git 存储库?

Git:如何检查新文件是否已添加到远程存储库,但未添加到本地

git丢弃专门更改暂存区

git - 获取自特定日期时间以来分支中的更改列表

git - 如何在 Git 中聚合 2 个分支

Visual Studio 中的 Git 多个存储库