Git文件夹提交错了,怎么撤销?

发布于:2025-02-10 ⋅ 阅读:(70) ⋅ 点赞:(0)

最近提交了一些不应该提交的文件夹到git中,现在需要移除它们,现在简单记录一下操作日志:

情况一

文件夹已经被添加到 Git,但未提交

如果文件夹已经被 git add 添加到暂存区中,但尚未提交,你可以使用以下命令将其从暂存区中移除:

git rm -r --cached <folder-name>

示例:

git rm -r --cached wrong-folder

效果:

  • 文件夹会从 Git 的暂存区中移除,但仍然保留在本地文件系统中。

如果操作正确,你就可以提交更改:

git commit -m "Remove wrong-folder from Git tracking"

情况二

如果文件夹已经被提交到 Git 仓库中,你需要从 Git 的历史记录中移除它:

步骤1:

使用以下命令将文件夹从 Git 仓库中移除:

git rm -r <folder-name>
步骤2:

将移除文件夹的操作提交到仓库:

git commit -m "Remove wrong-folder from Git repository"
步骤3:

将更改推送到远程仓库:

git push origin <branch-name>

情况三

只想停止跟踪某个文件夹,但保留本地文件夹

如果你希望 Git 停止跟踪某个文件夹,但不想删除本地文件夹,可以使用以下方法:

步骤1:

从 Git 中移除文件夹的跟踪

git rm -r --cached <folder-name>
步骤2:

将文件夹添加到 .gitignore 文件
为了防止文件夹再次被添加到 Git,请将它添加到 .gitignore 文件中。

echo "wrong-folder/" >> .gitignore
步骤3:

提交更改
提交 .gitignore 的更改以及停止跟踪的操作:

git add .gitignore
git commit -m "Ignore wrong-folder and stop tracking it"
步骤4:

推送更改到远程仓库

git push origin <branch-name>

情况四

文件夹已经被添加到远程仓库,但需要从整个仓库历史中移除

如果你想彻底从 Git 仓库中删除某个文件夹(包括所有提交历史),可以使用以下方法:
使用 git filter-repo:

  1. 确保安装了 Git 的 filter-repo 工具(取代了旧的 git filter-branch)。
  2. 使用以下命令彻底移除文件夹:
git filter-repo --path <folder-name> --invert-paths

总结:

场景 解决方法
文件夹被 git add,但未提交 git rm -r --cached
文件夹已经提交到仓库中 git rm -r 然后提交更改
停止跟踪文件夹,但保留在本地文件系统中 git rm -r --cached + 添加到 .gitignore
文件夹需要从整个历史记录中移除 使用 git filter-repo 或类似工具

网站公告

今日签到

点亮在社区的每一天
去签到