git回退版本

当我们commit了之后想回退,共有两个命令,四种组合。
包括git reset和git revert。其中git reset有三种模式:--mixed, --soft, --hard

假设你提交了一次,这次提交修改了changed.sh文件,你想回退这次修改。

HEAD指的当前位置,HEAD^1就是HEAD的上一次commit,HEAD^2就是上上次commit

  1. soft

--soft
Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

回退到之前的commit,并将修改放在暂存区。(这意味着你的暂存区如果有同名文件,那么暂存的修改会被冲刷掉),工作区不会有影响。

$ git reset --soft HEAD^1
$ git status
位于分支 main
您的分支与上游分支 'origin/main' 一致。

要提交的变更:
  (使用 "git restore --staged <文件>..." 以取消暂存)
        修改:     changed.sh
  1. mixed

--mixed
Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

回退到之前的commit,并将修改放在工作区。(不加参数默认是--mixed)
操作:
1. 清空暂存区,这意味着你在暂存区会被全部清空
2. 将受影响的文件放到工作区,保留changes
3. 如果工作区的文件和受影响的文件有重叠,不会覆盖工作区的文件

$ git reset HEAD^1
$ git status
位于分支 main
您的分支与上游分支 'origin/main' 一致。

尚未暂存以备提交的变更:
  (使用 "git add <文件>..." 更新要提交的内容)
  (使用 "git restore <文件>..." 丢弃工作区的改动)
        修改:     changed.sh
  1. git reset --hard

Resets the index and working tree. Any changes to tracked files in the working tree since are discarded. Any untracked files or directories in the way of writing any tracked files are simply deleted.

这样直接把HEAD指针回退,并且不会将两次commit的差异保存在工作区/暂存区中。会清空你的工作区和暂存区,应当慎用。一旦回退,除非记得之前的commit id,不然看不到之前的commit内容了。

$ git reset --hard HEAD^1
$ git status
位于分支 main
您的分支与上游分支 'origin/main' 一致。
posted @ 2024-03-22 19:36  王冰冰  阅读(20)  评论(4编辑  收藏  举报