Git - 删除操作
Git - 删除文件
Section titled “Git - 删除文件”要从你的 Git 仓库中删除文件,你应该使用 git rm 命令。这个命令不仅从你的工作目录 (working directory) 中删除文件,还会将删除操作添加到暂存区,这样 Git 就知道该文件是特意从版本控制 (version control) 中移除的。
简单地使用标准的 rm (Linux/macOS) 或 del (Windows) 命令删除文件,只会从你的工作目录中删除它。Git 会将其视为丢失的文件,你还需要再使用 git add 命令来添加删除操作。git rm 命令处理这两个步骤。
示例:删除已跟踪的文件
Section titled “示例:删除已跟踪的文件”想象 Tom 的项目不小心提交了一个名为 app_binary 的编译后的二进制文件,位于 bin/ 目录中。像 Git 这样的版本控制系统主要用于源代码,而不是编译产物。
当前状态:
[tom@dev-machine project]$ ls bin/app_binary helper_script.sh
[tom@dev-machine project]$ git status bin/app_binaryOn branch mainYour branch is up to date with 'origin/main'.
nothing to commit, working tree clean(assuming app_binary was previously committed)Tom 决定从仓库中删除 app_binary。他使用 git rm:
[tom@dev-machine project]$ git rm bin/app_binaryrm 'bin/app_binary'
[tom@dev-machine project]$ git statusOn branch mainYour branch is up to date with 'origin/main'.
Changes to be committed: (use "git restore --staged <file>..." to unstage) deleted: bin/app_binarygit status 输出显示 bin/app_binary 的删除操作已在暂存区。该文件也从 Tom 的工作目录中被移除。
Tom 现在提交 (commit) 这个变更:
[tom@dev-machine project]$ git commit -m "Remove compiled binary from version control"[main 5776472] Remove compiled binary from version control 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100755 bin/app_binary提交后,他应该将这个变更推送到远程仓库:
[tom@dev-machine project]$ git push origin main其他协作者在拉取 (pull) 后,该文件也将从他们的工作目录中移除,并且他们的 Git 历史将得到更新。
从暂存区移除文件但保留在本地
Section titled “从暂存区移除文件但保留在本地”有时,你可能不小心将文件添加到了暂存区 (staged)(例如,包含敏感数据的配置文件或大型日志文件),你不想提交 (commit) 它,但仍然想在你的工作目录中保留该文件。对于这种情况,请使用 git rm --cached <文件>。
[tom@dev-machine project]$ touch local_secrets.conf[tom@dev-machine project]$ git add local_secrets.conf
[tom@dev-machine project]$ git statusChanges to be committed: (use "git restore --staged <file>..." to unstage) new file: local_secrets.conf
[tom@dev-machine project]$ git rm --cached local_secrets.confrm 'local_secrets.conf'
[tom@dev-machine project]$ git statusUntracked files: (use "git add <file>..." to include in what will be committed) local_secrets.conf
[tom@dev-machine project]$ lslocal_secrets.conf # 文件仍保留在本地git rm --cached 命令将文件从暂存区移除(如果该文件过去已被提交,且你希望将来不再跟踪它,该命令也会将其从 Git 的跟踪中移除)。文件本身仍保留在你的工作目录中。你应该将这类文件添加到 .gitignore 文件中,以防止它们被再次不小心添加到版本控制中。
最佳实践 (Best Practice):使用 .gitignore 文件告诉 Git 忽略某些文件或目录(如编译后的二进制文件、日志文件、编辑器特定文件或依赖项文件夹,如 node_modules)。这从一开始就防止它们被不小心提交。