我有一个名为app.js的主分支。我在一个实验分支上对这个文件进行了更改。

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


当前回答

git checkout <branch_name> -- <paths>

更多信息

其他回答

git checkout master               -go to the master branch first
git checkout <your-branch> -- <your-file> --copy your file data from your branch.

git show <your-branch>:path/to/<your-file> 

希望这对你有所帮助。如果你有任何疑问,请告诉我。

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

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


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在其示例中使用了/to/app.js路径。

正如Frosty在评论中提到的:

您将只获得app.js的最新状态

但是,对于git checkout或git show,您实际上可以引用所需的任何修订,如SO问题“git gui中文件的git checkout-revision”所示:

$ 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

等等

施密特在评论中补充道:

你也可以从一个储藏处做到这一点:git签出存储--app.js如果您正在处理两个分支,并且不想提交,这非常有用。

要从另一个分支签出文件,只需简单的一行命令:

git checkout branch C:\path\to\file.cs

如果您想要多个文件

git checkout branch C:\path\to\file1.cs C:\path\to\file2.cs
git checkout branch_name file_name

例子:

git checkout master App.java

如果分支名称中有句点,则此操作将不起作用。

git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.

要从另一个分支恢复文件,只需使用工作分支中的以下命令:

git restore -s my-other-branch -- ./path/to/file

-s标志是source的缩写,即要从中提取文件的分支。

(所选的答案信息量很大,但也有点令人难以理解。)