删除也是一种操作,我们举例说明……
- 首先在工作区新建文件test.txt,并添加&提交到仓库
$ git add test.txt
$ git commit -m "add test.txt"
[master 8f28002] add test.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 test.txt
- 现在我们将文件手动从工作区删除,或者
rm <file>
命令删除
$ rm test.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: test.txt
no changes added to commit (use "git add" and/or "git commit -a")
删除了工作区的文件,导致工作区和版本库内容不一致,最终工作区和版本库是要保持一致的,所以需要确认,是跟工作区保持一致还是跟版本库保持一致
如果要跟工作区保持一致,让版本库得文件也被删除,直接
git commit
将工作区的修改提交到版本就可以了如果要跟版本库保持一致,找回工作区被删除的文件,直接
git checkout -- <file>
用版本库的版本替换工作区的版本,用git ls-files
查看当前文件的内容
$ git checkout -- test.txt
$ git status
On branch master
nothing to commit, working tree clean
$ git ls-files
README.txt
file1.txt
file2.txt
file3.txt
test.txt
git checkout -- <file>
其实是用版本库的版本替换工作区的版本,无论工作区是修改还是删除,都可以用命令“一键恢复”
小结
命令git rm用于删除一个文件。如果一个文件已经被提交到版本库,那么你永远不用担心误删,但是要小心,你只能恢复文件到最新版本,你会丢失最近一次提交后你修改的内容。
附图