git:从另一个分支签出到当前分支的文件(不要将HEAD切换到另一个分支)

Kac*_*che 43 git branch git-checkout

我想将另一个分支中存在的不同版本的文件加载到我当前的分支中.

git help checkout 说:

DESCRIPTION
   Updates files in the working tree to match the version in the index or
   the specified tree. If no paths are given, git checkout will also
   update HEAD to set the specified branch as the current branch.
Run Code Online (Sandbox Code Playgroud)

有没有办法检查所有这些文件,但更新HEAD?

Kac*_*che 57

通过提供当前路径进行结账.:

git checkout other-branch-name -- .

此操作类似于将HEAD切换到另一个分支而不检出文件,而只是从"其他方向".

正如@김민준所提到的,这会覆盖任何未提交的更改.如果需要,请记住先将它们存储或提交到某处.

  • 只是一个抬头,这将丢弃你所有未完成的工作.事后看来很明显,但是很难受:'( (4认同)

zyp*_*510 7

与@Kache的答案类似,但使用较新的git restore命令(需要Git版本2.23或更高版本):

git restore --source=<other-branch/tag/commit> <pathspec>
# or
git restore -s <other-branch/tag/commit> <pathspec>

# example: to load all files from branch "other"
git restore -s other .
Run Code Online (Sandbox Code Playgroud)

引入这个新命令是为了将“签出分支”和“签出文件”从单个git checkout命令中分离出来。阅读更多:命令是什么git restore