--- #领域/工具技巧 #复盘/0 ## 一句话描述 [___对单文件进行回滚操作_____] --- ```bash # 查看单一文件的提交记录 git log --oneline test.py ``` ## git resore 方法 Git 2.23+ ```bash git restore --source=HEAD~1 test.py git restore --source=f4g5h6j test.py git restore --source=f4g5h6jabcdef1234 test.py # 完整ID也可 ``` ## git checkout 旧版 Git 兼容 ```bash git checkout HEAD^1 -- test.py git checkout f4g5h6j -- test.py ``` # -------- RAG START ------- # Git单文件回滚操作步骤 ## 功能说明 利用 **Git** 命令行工具将指定单一文件回滚至历史提交的某个版本,适用于误操作后需要恢复特定文件的场景。 ## 前置准备 - 已安装 **Git** 且当前处于目标代码仓库目录下 - 确定需回滚的文件路径(如 `test.py`)及目标提交版本号(**Commit ID**) ## 执行步骤 1. **查看文件历史提交记录** 在终端运行命令查看该文件的版本历史,确认目标版本的 Commit ID: ```bash git log --oneline test.py ``` 2. **执行回滚操作** 根据本地 Git 版本选择对应的恢复指令。 - **Git 2.23+ (新特性推荐)** 使用 `git restore` 命令从指定来源恢复文件: ```bash # 回滚到上一个版本 git restore --source=HEAD~1 test.py # 回滚到指定短哈希 ID git restore --source=f4g5h6j test.py # 回滚到完整哈希 ID git restore --source=f4g5h6jabcdef1234 test.py ``` - **旧版 Git (兼容模式)** 使用 `git checkout` 命令进行覆盖恢复: ```bash # 回滚到父级版本 git checkout HEAD^1 -- test.py # 回滚到指定哈希 ID git checkout f4g5h6j -- test.py ``` ## 结果验证 - 终端无报错信息输出。 - 检查文件内容或运行 `git status`,确认 `test.py` 代码已变更为历史版本状态。 # -------- RAG END -------