来看看专业人员是如何使用Git的
大家好,这里是架构资源栈!点击上方关注,添加“星标”,一起学习大厂前沿架构!
在 GIT 中,有工作目录、暂存区、HEAD(Last Commit)的概念
工作目录 (WD) 磁盘上的实际文件 — 您在代码编辑器中看到的内容。反映所有更改(暂存 + 未暂存)。
暂存区 准备要提交的特定更改的预览区域。使用 git add 将更改移至此处。
HEAD 指向当前路径中最新提交的快照,这是最后您保存的状态。
当你需要从这些不同区域恢复和重置文件时,git恢复和重置命令是你的救星
**
Git 恢复
**
让我们看看如何使用 Git 恢复来恢复暂存文件(这些文件已经执行了 git add)和未暂存文件。
假设你编辑了file.txt,那么:
•You change some content
•You run git add file.txt → file is now staged
•You change it again → now it has staged AND unstaged changes
所以: •工作目录 (WD) ≠ 暂存区 (Index) ≠ 最后一次提交 (HEAD)
让我们探索不同的选项恢复👇
场景1:丢弃未暂存的本地更改
•Removes changes in your working directory
•Keeps what’s staged for commit
git restore file.txt
场景2:取消暂存文件(保留工作更改)
•Pulls file out of staging
•But keeps the working directory changes
git restore --staged file.txt
或者
git reset file.txt
场景3:完全重置文件(暂存 + 取消暂存)
•Fully resets the file to the last commit
•Clears both staging and working changes
git restore --staged --worktree file.txt 或者
git restore --source=HEAD --staged --worktree file.txt 场景4:从另一个分支带回文件
git restore --source origin/main file.txt 场景5:从另一个提交中恢复文件
git restore --source <commit-id> file.txt
**
Git重置
**
现在让我们深入研究 git Reset,看看如何使用 GIT Reset
GIT重置移动HEAD指针并修改暂存区和工作目录(任选)。
场景 1:撤消提交但保留所有更改
git reset --soft HEAD~1 •您提交得太早,但希望保留所有更改以便重新提交。 •提交已撤消。更改保留暂存状态。
场景2:撤消提交并取消暂存更改(但保留它们)
•You want to cancel the commit and decide which files to stage again.
•Commit is undone. Changes go back to the working directory, no longer staged.
git reset --mixed HEAD~1
场景3:撤消提交并放弃所有更改
•You want to completely remove the commit and lose all related changes.
•This deletes changes from both staging and working directory — no going back unless backed up.
git reset --hard HEAD~1
场景4:取消暂存特定文件(不影响其他文件)
•You added a file by mistake using git add, and want to unstage it.
•File is removed from staging, but your edits remain.
git reset file.txt
或者
git restore --staged file.txt
场景5:移动特定到提交(不是HEAD~1)
•You want to reset your branch to a known good commit.
•HEAD now points to abc1234, changes after that are moved to working directory.
**
Git 存储
**
在恢复和重置时,如果您需要存储任何更改,让我们看看几个用于存储的 git 命令
1. 主办所有数据库
git stash list 2. 查看存储内容(差异)
git stash show stash@{0} 3.详细差异如下:
git 储藏显示 -p 储藏@{0}
4. 恢复存储(应用它)或仅应用最近的存储:5. 恢复并删除存储 git stash apply stash@{0} git stash apply
使用pop瞬时应用和删除存储:
git stash pop stash@{0} 或者
git stash pop 6.删除特定的存储
git stash drop stash@{0} 7. 清除所有储藏
git stash clear



浙公网安备 33010602011771号