删除文件,一种是从工作区(Workspace)手动删除,另一种是用命令删除 。如果文件还是未跟踪状态,直接删除就可以了。否则还需要清除暂存区(Index / Stage)改变,提交至仓库区(Repository)(或版本区),最终同步至远程仓库(Repository)。
主要代码如下:
1 2 3
| git rm fileName or git rm -r mydir git commit -m "commit message" git push
|
详细介绍如下:
Git 本地数据管理,大概可以分为三个区:
工作区(Working Directory):是可以直接编辑的地方。
暂存区(Stage/Index):数据暂时存放的区域。
版本库(commit History):存放已经提交的数据。
工作区的文件 git add 后到暂存区,暂存区的文件 git commit 后到版本库。
rm 命令
执行命令:
rm 命令只是删除工作区的文件,并没有删除版本库的文件,想要删除版本库文件还要执行下面的命令:
1 2
| git add test.txt git commit -m "delete test"
|
git rm 命令
作用: 删除工作区文件,并且将这次删除放入暂存区。
注意: 要删除的文件是没有修改过的,就是说和当前版本库文件的内容相同,否则会出错。
再执行以下命令即可删除版本库文件:
1
| git commit -m "delete test"
|
git rm -f
作用: 删除工作区和暂存区文件,并且将这次删除放入暂存区。
注意: 要删除的文件已经修改过,就是说和当前版本库文件的内容不同。
- 文件修改过但还没 git add 到暂存区。
1 2 3 4 5 6
| D:\test>git rm data.txt error: the following file has local modifications: data.txt (use --cached to keep the file, or -f to force removal)
D:\test>
|
1 2 3 4 5 6 7 8
| D:\test>git add data.txt
D:\test>git rm data.txt error: the following file has changes staged in the index: data.txt (use --cached to keep the file, or -f to force removal)
D:\test>
|
可见文件修改后不管有没有 git add 到暂存区,使用 git rm 命令删除都会报错。
执行删除命令:
1
| D:\test>git rm -f data.txt
|
查看状态(成功删除工作区和暂存区文件,并且将这次删除放入暂存区。):
1 2 3 4 5 6 7 8 9
| D:\test>git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)
Changes to be committed: (use "git restore --staged <file>..." to unstage) deleted: data.txt D:\test>
|
然后提交:
1 2 3 4 5
| D:\test>git commit -m "delete data by -f" [master 8ff2f05] delete data by -f 1 file changed, 1 deletion (-) delete mode 100644 data.txt D:\test>
|
成功删除了版本库文件。
git rm –cached
作用: 删除暂存区文件,但保留工作区的文件,并且将这次删除放入暂存区。
执行删除命令:
1 2
| git rm --cached file rm file
|
然后提交:
1
| git commit -m "commit message"
|
成功删除了版本库文件。
结果: 删除了暂存区和版本库的文件,但保留了工作区的文件。如果文件有修改并 git add 到暂存区,再执行 git rm –cached 和 git commit,那么保留的工作区文件是修改后的文件,同时暂存区的修改文件和版本库的文件也被删了。