>> >> >> Reference << << << <<<<<<Ref>>>>>>
restore
Modified: 2025-12-31 | Author:ljf12825

git restore

Git2.23(2019)新增命令,它的目标是简化之前易混淆的git checkout用法,专门用于恢复文件

主要用法

1. 丢弃工作区的修改(尚未git add

git restore <file>

或者更明确地指定源(最后一次提交)

git restore --source=HEAD <file>

示例

# 修改了README.md,但想放弃修改
git restore README.md

# 恢复所有被修改的文件
git restore .

2. 取消暂存(已git add,但尚未git commit

git restore --staged <file>

示例

# 不小心把 debug.log 文件 add 了,想把它从暂存区移除
git restore --staged debug.log

# 取消暂存所有文件
git restore --staged .

3. 同时恢复工作区和暂存区

git restore --staged --worktree <file>
# 或者简化为
git restore -S -W <file>
# 或(因为 --source=HEAD 是默认值)
git restore -s HEAD -S -W <file>

4. 恢复到更早的提交版本

git restore --source=<commit-hash-or-branch> <file>

示例

# 发现当前的改动不对,想将 index.html 文件恢复到 3 次提交之前的状态
git restore -s HEAD~3 index.html

# 从另一个分支(比如 main)恢复一个文件到当前工作目录
git restore -s main some-file.js

常用参数

选项简写作用
--source-s指定恢复的源(提交、分支、标签)默认为HEAD
--staged-S只恢复暂存区。文件内容从源中取出,放入暂存区,不影响工作目录
--worktree-W只恢复工作目录。这是默认行为,通常可以省略
--patch-p交互式地选择要恢复的代码块