git 学习(3)文件删除恢复

时间:2023-03-09 07:01:31
git 学习(3)文件删除恢复

git学习(3)

撤销编辑

如果我们在编辑版本a的时候,如果在没有add之前,发现需要重新编辑版本a怎么办呢,可以通过git reset --hard comm_id, commit_id是版本a的提交号码,也可以通过git checkout --file命令来撤销工作区的修改,这里--很重要的,如果取消,就变成了创建新分支了。

$ git checkout --readme.txt

如果已经git add到暂存区了怎么办呢?

git status查看一下可以看到

On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage) modified: readme.txt

git提示我们可以通过git reset HEAD file来撤销暂存区

$ git reset HEAD readme.txt
Unstaged changes after reset:
M readme.txt

撤销暂存区的添加后,就回到了我们第一种情况了,现在该撤销工作区的修改了,使用git checkout --file即可

删除文件

先提交一个文件testrm

再通过rm删除这个文件

查看状态

$ 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: testrm no changes added to commit (use "git add" and/or "git commit -a")

我们有两个选择第一个是通过git rm file从版本库中删除,然后commit,第二个是从版本库恢复这个文件

删除

$ git rm testrm
rm 'testrm'
$ git commit -m "remove testrm"
[master e41a961] remove testrm
1 file changed, 1 deletion(-)
delete mode 100644 testrm

恢复

$ git checkout -- testrm

总结

可以看出对于提交过一次的文件,我们可以通过git checkout --file来恢复这个文件,不论你对这个文件做了什么