Files
Knowledge/1 使用/git/git 回滚常用命令.md
T

48 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
### 1. 撤销提交,但**保留所有修改**(最常用)
执行后,最近的提交会被撤销,但你的代码改动会**保留在工作区**,方便你修改后重新提交。
```bash
git reset --soft HEAD~1
```
### 2. 撤销提交,**取消暂存**,但保留修改
执行后,提交被撤销,代码改动保留,但会从暂存区(`git add` 的状态)退回到未暂存状态(即需要重新 `git add`)。
```bash
git reset HEAD~1
```
(注:`git reset --mixed HEAD~1` 是等价的,`--mixed` 为默认参数)
---
### 3. 彻底删除最后一次提交及所有改动(**危险操作**)
执行后,提交和所有代码改动都会**永久消失**(除非找回),请务必确认不需要这些改动了再执行。
```bash
git reset --hard HEAD~1
```
---
### 4. 如果已经推送到远程仓库(**安全方案**)
如果代码已经 `git push` 了,**不要用 `reset`**(强行推送会覆盖同事代码)。请使用 **`git revert`**,它会生成一个**新的提交**来反向撤销上次的内容,既安全又保留历史记录。
```bash
git revert HEAD
# 随后会自动弹出编辑器让你填写提交信息,保存即可
# 最后执行 git push 推送到远程
```
---
### 补充救急命令
如果你不小心执行错了(比如用了 `--hard` 删多了),**只要没执行 `git gc`**,可以在 **24小时内** 用以下命令找回:
```bash
git reflog
# 找到你想恢复的提交记录哈希值(如 a1b2c3d)
git reset --hard a1b2c3d
```
---
**总结建议**:
- 本地未推送 + 想保留修改 → 用 **方案 1**(`--soft`)
- 已推送到远程 → 用 **方案 4**(`revert`)
- 确定想彻底丢弃 → 用 **方案 3**(`--hard`),但请三思