git checkout master # first get back to master
git checkout experiment -- app.js # then copy the version of app.js
# from branch "experiment"
See also git how to undo changes of one file?
(另请参见git如何撤消对一个文件的更改?)
Update August 2019, Git 2.23: with the new git switch
and git restore
commands, that would be:
(更新2019年8月,Git 2.23:使用新的git switch
和git restore
命令,将是:)
git switch master
git restore -s experiment -- app.js
By default, only the working tree is restored.
(默认情况下,仅还原工作树。)
If you want to update the index as well (meaning restore the file content, and add it to the index in one command):
(如果您还想更新索引(意味着还原文件内容, 并通过一个命令将其添加到索引中):)
git restore -s experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -WS -- app.js
As Jakub Nar?bski mentions in the comments:
(正如雅库布·纳伦斯基(JakubNar?bski )在评论中提到的那样:)
git show experiment:path/to/app.js > path/to/app.js
works too, except that, as detailed in the SO question " How to retrieve a single file from specific revision in Git? ", you need to use the full path from the root directory of the repo.
(除SO问题“ 如何从Git中的特定修订版本检索单个文件? ”中详述的之外,该方法也可以工作,您需要使用来自仓库的根目录的完整路径。)
Hence the path/to/app.js used by Jakub in his example.
(因此,Jakub在他的示例中使用了path / to / app.js。)
As Frosty mentions in the comment:
(正如Frosty在评论中提到的那样:)
you will only get the most recent state of app.js
(您只会得到app.js的最新状态)
But, for git checkout
or git show
, you can actually reference any revision you want, as illustrated in the SO question " git checkout revision of a file in git gui ":
(但是,对于git checkout
或git show
,您实际上可以引用所需的任何修订版,如SO问题“ git gui中文件的git checkout修订版 ”所示:)
$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME
would be the same is $FILENAME is a full path of a versioned file.
($ FILENAME是版本文件的完整路径 ,将是相同的。)
$REVISION
can be as shown in git rev-parse
:
($REVISION
可以如git rev-parse
:)
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
and so on.
(等等。)
schmijos adds in the comments :
(schmijos添加了评论 :)
you also can do this from a stash:
(您也可以从隐藏处执行此操作:)
git checkout stash -- app.js
This is very useful if you're working on two branches and don't want to commit.
(如果您正在两个分支上并且不想提交,这将非常有用。)