下面以现实场景作为情境。
基础知识,理解git中的几个区域
本地代码已经add,未commit
修改本地工作目录中的readme.md,添加文字"第一次修改"
然后查看下状态
➜ experimentation 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")
进行Add操作,并查看状态
➜ experimentation git:(master) ✗ git add README.md
➜ experimentation 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
➜ experimentation git:(master) ✗
这时候,变动进入了缓存区(Index)
但是我们突然发现我们改动错了,其实我是想改动experimentation.txt
文件。
方法一:我们当然可以再次修改experimentation和readme文件(删除readme中的修改,给experimentation中添加“第一次修改”),然后再Add
方法二:我们想的可能是撤回之前的add操作,然后给experimentation中添加“第一次修改”,然后再次Add
,那这样的话,我们如何操作呢?
撤销某个add文件:
git reset HEAD <filename>
撤销全部add文件:
git reset HEAD .
➜ experimentation git:(master) ✗ git reset HEAD README.md
Unstaged changes after reset:
M README.md
➜ experimentation 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")
Tip
git log与git reflog的区别
git reflog 可以查看所有分支的所有操作记录(包括commit,reset的操作,已经被删除的commit记录)
git log不能察看已经删除的commit记录
git log与git reflog的区别
git reflog 可以查看所有分支的所有操作记录(包括commit,reset的操作,已经被删除的commit记录)
git log不能察看已经删除的commit记录
本地代码已经add,已commit
将本地代码多commit几次,再来看下我们的提交log
- 方法一(推荐):执行
git revert <commitId>
撤回到指定的版本,包括文件和状态。
- 方法二:执行
git reset <commitId>
➜ experimentation git:(master) git reset 2a6c701
Unstaged changes after reset:
M experimentation.txt
➜ experimentation git:(master) ✗ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 4 and 6 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
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: experimentation.txt
no changes added to commit (use "git add" and/or "git commit -a")
回退至指定的版本,区别如下
Tip
git revert与git reset的区别
git reset是直接删除指定的commit之前的所有commit(这是不安全的,特别是push后),把HEAD向后移动。
git revert是一次新的commit,HEAD继续前进,与普通的commit一样。
git revert与git reset的区别
git reset是直接删除指定的commit之前的所有commit(这是不安全的,特别是push后),把HEAD向后移动。
git revert是一次新的commit,HEAD继续前进,与普通的commit一样。