成为git砖家(6): git restore 命令
创始人
2024-12-05 05:05:22

文章目录

    • 1. git restore 命令是新命令
    • 2. git官方对于restore命令的说明
    • 3. 总结

1. git restore 命令是新命令

在2019年8月发布的 Git 2.23 版本中,git checkout 命令的功能被拆解到两个新的命令中:

  • git switch: 负责分支相关的操作
  • git restore: 负责文件相关的操作

https://stackoverflow.com/questions/58003030/what-is-git-restore-and-how-is-it-different-from-git-reset

相应的,当我们修改了文件,在 git status 命令给出的提示中看到的提示命令, 也变了:

  • 以往会提示 git reset -- 来恢复 stage 区域的内容, 现在则提示 git restore --staged ;
  • 以往会提示 git checkout -- 来恢复 working directory 的内容,现在则提示 git restore

遗憾的是, 一些经典的教程尚未做更新,我们只能手动改一下, 例如图解 git 里的: https://marklodato.github.io/visual-git-guide/index-en.html
在这里插入图片描述
不过,stackoverflow 上的问答中也有人给出了更好的图解:

在这里插入图片描述

2. git官方对于restore命令的说明

https://git-scm.com/docs/git-restore

Restore specified paths in the working tree with some contents from a restore source. If a path is tracked but does not exist in the restore source, it will be removed to match the source.

在工作目录中用恢复源中的内容恢复指定的路径。如果某个路径被跟踪但在恢复源中不存在,它将被删除以匹配源内容。

The command can also be used to restore the content in the index with --staged, or restore both the working tree and the index with --staged --worktree.

该命令也可以使用 --staged 恢复索引中的内容,或者使用 --staged --worktree 同时恢复工作区和索引。

By default, if --staged is given, the contents are restored from HEAD, otherwise from the index. Use --source to restore from a different commit.

默认情况下,如果使用了–staged选项,内容会从HEAD恢复,否则会从索引恢复。使用–source选项可以从不同的提交中恢复。

See “Reset, restore and revert” in git[1] for the differences between the three commands.

很遗憾,截至目前(2024年7月28日),git 官方在线文档里仍然标记 restore 命令为实验性质:

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

3. 总结

一些经典教程中使用了 git reset git checkout 来分别恢复 staging area 和 working directory 内容, 虽然git保持了兼容性,但是新版的git(>=2.23)的 git status 命令给出的提示,是让大家用 git restore --stagedgit restore 两个命令作为替代。

相关内容

热门资讯

无源物联网深度解析:无电池联网... 你是否想过,有一天我们身边的智能设备再也不需要换电池、再也不怕没电? 从智能门锁到可穿戴设备,从环...
2026年惠州“发改讲堂”第4... 为抢抓人工智能发展战略机遇,提升干部队伍专业素养,助力我市人工智能与机器人产业创新发展,5月9日,惠...
华为申请信息传输方法专利,能够... 国家知识产权局信息显示,华为技术有限公司申请一项名为“信息传输方法、通信装置及存储介质”的专利,公开...
2026沪港创新项目评选启动仪... 来源:滚动播报 (来源:上观新闻) 5月12日,2026沪港创新项目评选启动仪式在大零号湾海创城举...