Git reset 的hard、soft、mixed参数对比
分区概念
先要清楚在本地,git会分三个区:工作区、暂存区、本地库。
当使用去做版本移动的时候,那么在使用【--hard】、【--mixed】、【--soft】是不一样的。
1. --soft参数
## 这里的log commit id 要写到前一次commit id
git reset --soft abcdef
- 仅仅移动本地库
HEAD指针
不仅把指针移动到本地库,同时还把提交到工作区的代码回退到暂存区。也就是说把已经commit提交到工作区的代码,回退到暂存区,现在变成了绿色,即已经【add】操作,但未做【commit】操作。之前修改的代码又还原回来了。

操作示例
- 已经commit 代码到工作区 add login log
- 想回退代码,查看提交的commit id
- 操作回退 git reset --soft abcdef ## 这里的log commit id 要写到前一次commit id ,即:ca2f3c6aa5cdf99f6c6de82bb2967166843ae36c
操作步骤
# 1. 查看提交的commit id
$ git log
commit 9ee8d1dba1005a7c77d9bea5361945cb3887d326 (HEAD -> main)
Author: wanghaima <whm2416@qq.com>
Date: Thu Jan 2 17:32:20 2025 +0800
add login log
commit ca2f3c6aa5cdf99f6c6de82bb2967166843ae36c
Merge: 6e127e3b afa7b822
Author: moumou Lee <490227076@qq.com>
Date: Mon Dec 30 17:43:54 2024 +0800
1230正式服更新
# Conflicts:
# application/api/controller/Logistics.php
# 2. 操作回退 git reset --soft abcdef 这里的log commit id 要写到前一次commit id ,即:ca2f3c6aa5cdf99f6c6de82bb2967166843ae36c
Administrator@WIN-20240929XKQ MINGW64 /d/code/php/youtaikeji/ytss_server (main)
$ git reset --soft ca2f3c6aa5cdf99f6c6de82bb2967166843ae36c
Administrator@WIN-20240929XKQ MINGW64 /d/code/php/youtaikeji/ytss_server (main)
# 3. 查看回退情况
$ git status
On branch main
Your branch is behind 'origin/main' by 3 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: application/api/controller/Organizations.php

到此已经回退成功
2. --mixed参数
git reset --mixed abcdef 要写到前一次commit id
- 移动本地库
HEAD指针 - 重置暂存区
不仅把指针移动到本地库,同时还把暂存区的代码也做了移动。也就是说把已经commit提交到工作区的代码直接回退到本地库,现在变成了红色,即未做【add】操作状态。之前修改的代码又还原回来了。如果不写--mixed,默认也是此参数。

3. --hard参数
git reset --hard abcdef
- 移动本地库
HEAD指针 - 重置暂存区
- 重置工作区
不用解释了,除了上面描述的,同时你本地的代码就是你回退的版本代码。

不过很多时候,我们在回退更多的是要保留本地代码的,即使用--mixed参数。除非你是重新拉取一份,那可以使用--hard参数。
参考文章:https://blog.csdn.net/weixin_42740530/article/details/115914113
[Haima的博客]
http://www.cnblogs.com/haima/

浙公网安备 33010602011771号