git: checkout files from another branch into current branch (don't switch HEAD to the other branch)

GitBranchGit Checkout

Git Problem Overview


I want to load a different version of the files that exist in another branch into my current branch.

git help checkout says:

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.

Is there a way to checkout all those files, but not update HEAD?

Git Solutions


Solution 1 - Git

checkout by providing the current path, .:

git checkout other-branch-name -- .

This operation is similar to switching HEAD to another branch without checking out files, but just from the "other direction".

As @김민준 mentions, this overwrites any uncommitted changes. Remember to either stash or commit them somewhere first if needed.

Solution 2 - Git

Similar to @Kache's answer, but using the newer git restore command (requires Git version 2.23 or above):

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 .

This new command was introduced to split "checking out a branch" and "checking out files" out of the single git checkout command. Read more: What is the git restore command.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKacheView Question on Stackoverflow
Solution 1 - GitKacheView Answer on Stackoverflow
Solution 2 - Gituser5532169View Answer on Stackoverflow