我把以前由 Git 跟踪的文件放在.gitignore 列表中. 但是,文件在编辑后仍然显示在 git 状态。


当前回答

這不再是最新 Git 的問題(v2.17.1 在寫作時)。

.gitignore 文件最终忽略了跟踪但删除的文件. 您可以通过运行下列脚本来为自己测试此文件. 最终 git 状态声明应该报告“没有任何承诺”。

# Create an empty repository
mkdir gitignore-test
cd gitignore-test
git init

# Create a file and commit it
echo "hello" > file
git add file
git commit -m initial

# Add the file to gitignore and commit
echo "file" > .gitignore
git add .gitignore
git commit -m gitignore

# Remove the file and commit
git rm file
git commit -m "removed file"

# Reintroduce the file and check status.
# .gitignore is now respected - status reports "nothing to commit".
echo "hello" > file
git status

其他回答

复制/复制(单线)的答案是:

git rm --cached -r .; git add .; git status; git commit -m "Ignore unwanted files"

这个命令不会改变.gitignore 文件的内容. 它只会忽略已承诺到 Git 存储库的文件,但现在我们已经添加到.gitignore。

命令 git 状态; 只需审查更改,可以下载。

最终,它将立即通过“不要错过不需要的文件”的消息进行更改。

如果您不希望承诺更改,请放下命令的最后一部分(git commit -m “不要错过不需要的文件”)

這不再是最新 Git 的問題(v2.17.1 在寫作時)。

.gitignore 文件最终忽略了跟踪但删除的文件. 您可以通过运行下列脚本来为自己测试此文件. 最终 git 状态声明应该报告“没有任何承诺”。

# Create an empty repository
mkdir gitignore-test
cd gitignore-test
git init

# Create a file and commit it
echo "hello" > file
git add file
git commit -m initial

# Add the file to gitignore and commit
echo "file" > .gitignore
git add .gitignore
git commit -m gitignore

# Remove the file and commit
git rm file
git commit -m "removed file"

# Reintroduce the file and check status.
# .gitignore is now respected - status reports "nothing to commit".
echo "hello" > file
git status

把它移动出来,承诺,然后把它移动回来。

这对我来说在过去已经工作了,但可能有更“迷人的”方式来实现这一点。

答案来自Matt Frear是最有效的IMHO. 下面只是一个PowerShell脚本给那些在Windows只删除文件从他们的Git存储库,符合他们的排除列表。

# Get files matching exclusionsfrom .gitignore
# Excluding comments and empty lines
$ignoreFiles =  gc .gitignore | ?{$_ -notmatch  "#"} |  ?{$_ -match  "\S"} | % {
                    $ignore = "*" + $_ + "*"
                    (gci -r -i $ignore).FullName
                }
$ignoreFiles = $ignoreFiles| ?{$_ -match  "\S"}

# Remove each of these file from Git
$ignoreFiles | % { git rm $_}

git add .

git update-index 为我做工作:

git update-index --assume-unchanged <file>

注意: 这个解决方案实际上是独立的.gitignore 因为 gitignore 仅适用于未追踪的文件。


更新,更好的选择

因为这个答案被发布,一个新的选项已经创建,应该是优先的. 你应该使用 --skip-worktree 这是为修改的跟踪文件,用户不想再承诺,并保持 --assume-unchanged 性能,以防止 git 检查大跟踪文件的状态. 查看 https://stackoverflow.com/a/13631525/717372 更多详细信息...

git update-index --skip-worktree <file>

取消

git update-index --no-skip-worktree <file>