如何从另一个分支只获取一个文件? [英] How to get just one file from another branch?

查看:32
本文介绍了如何从另一个分支只获取一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Git 并在 master 分支上工作.这个分支有一个名为 app.js 的文件.

I am using Git and working on master branch. This branch has a file called app.js.

我有一个 experiment 分支,我在其中进行了大量更改和大量提交.现在我想将所有仅对 app.js 所做的更改从 experiment 带到 master 分支.

I have an experiment branch in which I made a bunch of changes and tons of commits. Now I want to bring all the changes done only to app.js from experiment to master branch.

我该怎么做?

再一次,我不想合并.我只想将 app.js 中的所有更改从 experiment 分支带到 master 分支.

Once again I do not want a merge. I just want to bring all the changes in app.js from experiment branch to master branch.

推荐答案

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

另见 git 如何撤消对一个文件的更改?

使用新的 git switchgit restore 命令,即:

With the new git switch and git restore commands, that would be:

git switch master
git restore --source 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 --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 问题中详述的那样如何从 Git 中的特定修订版中检索单个文件?",您需要使用 repo 根目录中的完整路径.
因此,Jakub 在他的示例中使用了 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.
Hence the path/to/app.js used by Jakub in his example.

正如 Frosty 在评论中提到的:

As Frosty mentions in the comment:

你只会得到 app.js 的最新状态

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

但是,对于 git checkoutgit show,您实际上可以引用您想要的任何修订版本,如 SO 问题git checkout git gui 中文件的修订版":

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 show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME

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

would be the same is $FILENAME is a full path of a versioned file.

$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 增加了 在评论中:

您也可以从存储中执行此操作:

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.

这篇关于如何从另一个分支只获取一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆