在使用Git工具管理底代码的版本迭代时,总有那么几个瞬间由于清奇的脑回路导致提交的代码没有达到自己满意的的效果,因此就需要回退到指定的提交记录位置出,重新编写后在提交。这是就需要用到`git reset`命令了。
```shell
$ git reset [--soft | --mixed | --hard] [HEAD]
```
`git reset`命令有三个参数可以选择:
- `--soft`:回滚到某一个指定提交记录处,但不删除该记录之后的记录;
- `--mixed`:默认选项,回滚到上一次的提交记录处,不删除该当前修改;
- `--hard`:和soft功能类似,但是会删除指定提交记录之后的所有记录。
个人建议不要使用 `-mixed`和`--hard`选项,容易导致已修改记录丢失,同时也不建议使用`HEAD`指定回滚的位置,容易搞错回滚的位置,直接使用`commit`记录的唯一标识字符串就行了,简单明了。
以下面的项目为例,在本地的提交记录如下:
```shell
面条@▒▒▒▒ MINGW64 /f/Git/test (main)
$ git log
commit ae54e78bfb0da1b24e0cdfc923065838b99f1e57 (HEAD -> main, origin/main, origin/HEAD)
Author: miantiao5115 <1784855370@qq.com>
Date: Thu Sep 23 22:38:34 2021 +0800
add another gpx file
commit 9e761f00d5f3f8258a2c7860babed1818b2f96dc
Author: miantiao5115 <1784855370@qq.com>
Date: Thu Sep 23 22:36:32 2021 +0800
delete a gps point of test.gpx
commit 672268c0bd99fb74c46663bd1037d359d17c911c
Author: miantiao5115 <1784855370@qq.com>
Date: Thu Sep 23 22:34:44 2021 +0800
add a gpx file
commit 1101570ed04f64cd67d0385c93f68ecfbbf8414e
Author: miantiao5115 <1784855370@qq.com>
Date: Thu Sep 23 22:33:21 2021 +0800
add a picture
commit a31fa0c35b4cc6d61a24720852b57dbc14f4103f
Author: miantiao <1784855370@qq.com>
Date: Thu Sep 23 22:31:18 2021 +0800
Initial commit
```
在github上的提交记录如下:
![image.png](https://miantiao.online/upload/2021/09/image-5655833742cc4d4ab59d93bd9e8c5d88.png)
现在,如果`delete a gps point of test.gpx`这条提交记录修改的不如意,想重新修改,那么就可以通过下面命令回退到它的上一个提交记录处:
```shell
$ git reset 672268c0bd99fb74c46663bd1037d359d17c911c
```
这时,再执行`git status`命令就会发现已经回滚了,并且没有删除第一个和第二个提交记录
```shell
$ git status
On branch main
Your branch is behind 'origin/main' by 2 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
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: test.gpx
Untracked files:
(use "git add <file>..." to include in what will be committed)
test2.gpx
no changes added to commit (use "git add" and/or "git commit -a")
```
本地本地回滚改成功了,那么远端也想回滚怎么办?
很简单,直接强制将本地push到远端,即执行下面命令:
```shell
$ git push -f
```
执行完成 ,再去远端查看发现已经回滚了
![image.png](https://miantiao.online/upload/2021/09/image-674ef0f2e8d841f69f1d87f9adb551f8.png)
![Git回滚远端和本地的commit记录](https://miantiao.online/upload/2020/3/papyros-wallpaper%205-6f3175463db8482cb1c41b38b0805d80.png)
Git回滚远端和本地的commit记录