跳转至

Git 常用命令

撤销还没提交的改动

git restore path/to/file        # 丢弃未 add 的修改
git restore --staged path/to/file   # 取消暂存,保留改动
git restore path/to/file           # 再丢弃改动
git reset --soft HEAD~1   # 撤销提交,改动回到暂存区
git reset --mixed HEAD~1  # 撤销提交,改动回到工作区(默认)

已经 push 过

不要 reset 后强推公共分支。用反向提交:git revert <sha>,历史可追溯。

找回"消失"的提交

git reflog                 # 所有 HEAD 移动记录
git branch rescue <sha>    # 找到目标后拉个分支保住它

reflog 默认保留 90 天,误删分支通常都能救回来。

清理已合并分支

git branch --merged main | grep -v -E '^\*|main' | xargs -r git branch -d

查看某行是谁改的

git blame -L 20,40 path/to/file
git log -S "关键字符串" --oneline   # 按内容变化反查提交