Linux git(7)----删除文件

17 篇文章 0 订阅
用到的新命令
1.git rm test.txt:确实要从版本库中删除该文件,那就用命令git rm删掉,并且git commit

在Git中,删除也是一个修改操作
1.先添加一个文件test.txt
[root@VM_0_11_centos learn_git]# vim test.txt
delete file
[root@VM_0_11_centos learn_git]# git add test.txt
[root@VM_0_11_centos learn_git]# git commit -m "add test.txt"
[master 0142aa9] add test.txt
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

2.直接删除文件
[root@VM_0_11_centos learn_git]# rm test.txt 
rm: remove regular file ‘test.txt’? y
[root@VM_0_11_centos learn_git]# git status    
<==Git知道你删除了文件,因此,工作区和版本库就不一致了,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")

3.现在你有两个选择,
a:确实要从版本库中删除该文件,那就用命令git rm删掉,并且git commit:
[root@VM_0_11_centos learn_git]# git rm test.txt
rm 'test.txt'
[root@VM_0_11_centos learn_git]# git commit -m "delete test.txt"
[master f781044] delete test.txt
 1 file changed, 1 deletion(-)
 delete mode 100644 test.txt
现在,文件就从版本库中被删除了

这种情况下git checkout -- text.txt
[root@VM_0_11_centos learn_git]# git checkout -- text.txt    <== 提示不存在该文件
error: pathspec 'text.txt' did not match any file(s) known to git.
要是想要恢复之前版本的数据,可以参考<版本回退>那篇,使用git reset --hard commit id,如这里text.txt之前版本的commit id用git log查看是4ab772a21b366...,所以
[root@VM_0_11_centos learn_git]# git reset --hard 4ab772a21b366
HEAD is now at 4ab772a add text.txt
[root@VM_0_11_centos learn_git]# ls
LICENSE  readme.txt  text.txt    <== text.txt又回来了


b.删错了,因为版本库里还有呢,所以可以很轻松地把误删的文件恢复到最新版本:
[root@VM_0_11_centos learn_git]# rm text.txt <== 删除文件
rm: remove regular file ‘text.txt’? y
[root@VM_0_11_centos learn_git]# ls    
LICENSE  readme.txt    <== text.txt已被删除,但版本库中还在
[root@VM_0_11_centos learn_git]# git checkout -- text.txt
[root@VM_0_11_centos learn_git]# ls
LICENSE  readme.txt  text.txt    <== text.txt又回来了


git checkout其实是用版本库里的版本替换工作区的版本,无论工作区是修改还是删除,都可以“一键还原”。
git rm用于删除一个文件。如果一个文件已经被提交到版本库,那么你永远不用担心误删,但是要小心,你只能恢复文件到最新版本,你会丢失最近一次提交后你修改的内容。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值