git checkout main # first get back to main
git checkout experiment -- app.js # then copy the version of app.js
# from branch "experiment"
也可以看看撤消 Git 中一个文件的工作副本修改 https://stackoverflow.com/q/692246/6309.
2019 年 8 月更新,Git 2.23
随着新git switch https://stackoverflow.com/a/57066202/6309 and git restore https://stackoverflow.com/a/57066072/6309命令,那就是:
git switch main
git restore --source experiment -- app.js
默认情况下,仅恢复工作树。
如果您还想更新索引(意味着恢复文件内容,and通过一个命令将其添加到索引中):
git restore --source experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -SW -- app.js
As 雅库布·纳伦布斯基 https://stackoverflow.com/users/46058/jakub-narebski评论中提到:
git show experiment:path/to/app.js > path/to/app.js
也有效,除此之外,如 SO 问题中所述“如何从 Git 中的特定修订版检索单个文件? https://stackoverflow.com/questions/610208/how-to-retrieve-a-single-file-from-specific-revision-in-git/610315#610315”,您需要使用存储库根目录的完整路径。
因此,Jakub 在他的示例中使用了 path/to/app.js。
As Frosty https://stackoverflow.com/users/7476/frosty评论中提到:
你只会得到 app.js 的最新状态
但对于git checkout
or git show
,您实际上可以参考您想要的任何修订,如SO问题所示“git checkout git gui 中文件的修订版本 https://stackoverflow.com/questions/1507300/git-checkout-revision-of-a-file-in-git-gui/1507678#1507678":
$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME
与 $FILENAME 相同完整路径版本化文件的。
$REVISION
可以如图所示git rev-parse http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html:
experiment@{yesterday}:app.js # app.js as it was yesterday
experiment^:app.js # app.js on the first commit parent
experiment@{2}:app.js # app.js two commits ago
等等。
schmijos https://stackoverflow.com/users/430418/schmijos adds 在评论中 https://stackoverflow.com/questions/2364147/how-to-get-just-one-file-from-another-branch/2364223#comment93480592_2364223:
您也可以从藏匿处执行此操作:
git checkout stash -- app.js
如果您正在处理两个分支并且不想提交,这非常有用。