我正在使用git并在master分支上工作。这个分支有一个名为app.js
的文件。
我有一个experiment
分支,其中我做了一堆变化和大量的提交。现在我想把所有的改变只做到app.js
从experiment
到master
分支。
我怎么做?
再一次,我不想合并。我只想把app.js
的所有变化从experiment
分支带到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?
正如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 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
等等。
你也可以从藏匿处做到这一点:
git checkout stash -- app.js
如果您正在处理两个分支并且不想提交,那么这非常有用。
一切都更简单,使用git checkout。
假设you're on master
分支,得到app.js from new-feature
分支做:
git checkout new-feature path/to/app.js
// note that there is no leading slash in the path!
这将为您带来所需文件的内容。您可以像往常一样使用sha1的一部分而不是新功能分支名来获取该特定提交中的文件。
补充VonC和chhh的答案。
git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative than just use
git show experiment:app.js > app.js
要么
git checkout experiment -- app.js
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 checkout <branch name> -- .
这是一种实用的方法,不直接回答OP,但有些已经发现有用:
如果有问题的分支在GitHub上,那么您可以使用GitHub提供的任何工具导航到所需的分支和文件,然后单击“原始”以查看纯文本,并(可选)将文本复制并粘贴为期望。
我喜欢这种方法,因为它可以让您在将远程文件拉到本地计算机之前完整地查看它。