我有一个名为app.js的主分支。我在一个实验分支上对这个文件进行了更改。
我只想将实验中对app.js所做的更改应用到master分支。
我有一个名为app.js的主分支。我在一个实验分支上对这个文件进行了更改。
我只想将实验中对app.js所做的更改应用到master分支。
当前回答
补充VonC和chhh的答案:
git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative, then just use:
git show experiment:app.js > app.js
or
git checkout experiment -- app.js
其他回答
补充VonC和chhh的答案:
git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative, then just use:
git show experiment:app.js > app.js
or
git checkout experiment -- app.js
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
如果您想要来自特定提交(任何分支)的文件,请说06f8251f
git checkout 06f8251f path_to_file
例如,在Windows上:
git checkout 06f8251f C:\A\B\C\D\file.h
git checkout <branch_name> -- <paths>
更多信息