git - 如何从另一个分支获取一个文件?

标签 git git-branch git-checkout

我有一个 master 分支,其中有一个名为 app.js 的文件。我在 experiment 分支上对此文件进行了更改。

我只想将 experiment 中对 app.js 所做的更改应用到 master 分支上。

最佳答案

git checkout master               # first get back to master
git checkout experiment -- app.js # then copy the version of app.js 
                                  # from branch "experiment"

另见 git how to undo changes of one file?


2019 年 8 月更新,Git 2.23

有了新的git switchgit restore命令,那就是:

git switch master
git restore --source experiment -- app.js

默认情况下,只有工作树被恢复。
如果您还想更新索引(意味着恢复文件内容,用一个命令将其添加到索引):

git restore --source experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -SW -- app.js

作为Jakub Narębski评论中提到:

git show experiment:path/to/app.js > path/to/app.js

也有效,除了如 SO 问题“How to retrieve a single file from specific revision in Git?”中所述,您需要使用 repo 根目录的完整路径。
因此,Jakub 在他的示例中使用了 path/to/app.js。

作为Frosty评论中提到:

you will only get the most recent state of app.js

但是,对于 git checkoutgit show,您实际上可以引用您想要的任何修订,如 SO 问题“git checkout revision of a file in git gui”中所示:

$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME

$FILENAME 是版本化文件的完整路径

$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

等等。

schmijos添加 in the comments :

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.

关于git - 如何从另一个分支获取一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2364147/

相关文章:

git - 使用 github.com 查看文件的更改历史

php - 使用 GIT 的 php 项目组织的最佳实践?

git - 如何查找由提交消息更改的文件

git - 我如何只提交一些文件?

Git 更改分支,但不更改工作区中的文件

git - 我所在的文件夹在 git 中有什么意义吗?

git - svn 到 git 的转换 : Correct remote ref must start with 'refs/' error

git checkout : detailed meaning of "theirs" and "ours"

Git:pathspec 'path' 与 git 已知的任何文件都不匹配

git - --git checkout 中的试运行选项