git的一些撤销操作

20次阅读

共计 1506 个字符,预计需要花费 4 分钟才能阅读完成。

前言

在用开发项目的时候,经常会写着写着会发现写错的时候,人生没有后悔药,但是 git 有啊,大不了从头再来嘛。

git 的一些撤销操作

代码还没有存到暂存区

当我们修改了一个文件,还没有执行 git add 操作的时候,发现写错的时候.

➜  xiaoyan_es_static git:(master) ✗ cat README.md
es 日志统计查询
我写错了, 不想要这行了 

我们可以使用如下命令,回到最后一次提交的版本

git checkout -- <file>...

执行完 git checkout — README.md 命令后

➜  xiaoyan_es_static git:(master) ✗ cat README.md
es 日志统计查询 

代码存储到了暂存区

当我们一不小心将代码存入了暂存区

➜  xiaoyan_es_static git:(master) ✗ git add .
➜  xiaoyan_es_static git:(master) ✗ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   README.md

我们可以使用如下命令,回到最后一次提交的版本

git reset HEAD <file>...

执行完命令后如下所示

➜  xiaoyan_es_static git:(master) ✗ cat README.md 
es 日志统计查询
这行写错了,但是已经存到暂存区了 %                                                                                                                                                                         ➜  xiaoyan_es_static git:(master) ✗ git status              
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

代码已经 commit 了

当我们修改的代码已经 commit 了,我们只需要执行

➜  xiaoyan_es_static git:(master) git reset --hard HEAD^

上一个版本就是 HEAD^,上上一个版本就是 HEAD^^,当然往上 100 个版本写 100 个 ^ 比较容易数不过来,所以写成 HEAD~100。

代码已经 push 到远程了

少年,你怎么这么冲动呢

git 的一些其它操作

当我们需要删除暂存区或分支上的文件, 同时工作区也不需要这个文件了, 可以使用

git rm file_path
git commit -m 'delete somefile'
git push

当我们需要删除暂存区或分支上的文件, 但本地又需要使用, 只是不希望这个文件被版本控制, 可以使用

git rm --cached file_path
git commit -m 'delete remote somefile'
git push

当我们对文件或者文件夹执行过 chmod 操作时,执行 git diff 会出现类似 ’ old mode xxx new mode xxx’, 这个时候我们只需要执行如下命令即可

git config --add core.filemode false

这样你的所有的 git 库都会忽略 filemode 变更了~

更多文章欢迎关注博客:https://www.zplxjj.com 和公众号

正文完
 0