在Git中,删除也是一个修改操作,我们实战一下,先添加一个新文件test.txt到Git并且提交:
创建一个文件test.txt,写入一句话`this is new file !`.
$ echo 'this is new file !' >> test.txt
$ cat test.txt
this is new file !
执行命令`git add`告诉Git,添加文件到暂存区
$ git add test.txt
warning: LF will be replaced by CRLF in test.txt.
The file will have its original line endings in your working directory
执行命令`git commi`告诉Git,提交文件到暂存区
$ git commit -m'test.txt'
[master 1ef1f08] test.txt
1 file changed, 1 insertion(+)
create mode 100644 test.txt
推送到Github远程仓库
$ git push origin master
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 322 bytes | 322.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To 1168:apollo1168/1168.git
2c49e4f..1ef1f08 master -> master
一般情况下,你通常直接在文件管理器中把没用的文件删了,或者用rm命令删了.
$ rm test.txt
这时,Git知道你删除了文件,因此,工作区和版本库就不一致了,git status命令会立刻告诉你哪些文件被删除了.
$ 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")
现在你有两个选择:
1.从版本库中删除该文件,命令git rm删掉,并且git commit;
2.从版本库里面,把误删的文件恢复到最新版本,命令git checkout -- filename;
从版本库中删除该文件
$ git rm test.txt
rm 'test.txt'
$ git commit -m "delete test.txt ..."
[master 1a97ea4] delete test.txt ...
1 file changed, 1 deletion(-)
delete mode 100644 test.txt
从版本库中恢复文件
其实是用版本库里的版本替换工作区的版本,无论工作区是修改还是删除,都可以“一键还原”.
git checkout -- filename