我有一个 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 switch
和 git 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 checkout
或 git 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
等等。
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/