36

git的一些撤销操作

 4 years ago
source link: https://www.tuicool.com/articles/IriiMfr
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在用开发项目的时候,经常会写着写着会发现写错的时候,人生没有后悔药,但是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变更了~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK