29

I am trying to git checkout a single file from another branch.

Everything is fine, but it puts the file in the same directory tree of the branch that I am checking out.

There is a way to specify a different destination folder during git checkout?

This is what I did:

git checkout other_branch -- path/to/file/xxx

git status:

new file:             path/to/file/xxx

this the result I need (put xxx into the root directory of my working branch):

new file:             ./xxx
fromthestone
  • 1,217
  • 2
  • 13
  • 16
  • Can you explain why you want to check out a file in a different path? You say, "in the root directory of my working branch." In a Git repo, different branches exist in the same directory. It seems like you may be using Git in a way that it was not designed for. – Craig Finch Sep 01 '21 at 19:41
  • 1
    This answer involving git show is the right one, IMO https://stackoverflow.com/a/888623/192737 – Jeff Trull Jun 02 '22 at 03:57

3 Answers3

38

You have 2 options

  1. chain 2 commands, git checkout other_branch -- file.txt && git mv file.txt folder/file.txt
  2. or you can use worktree
Avi Fatal
  • 1,550
  • 8
  • 8
4

You should be able to just move the file, e.g. in Linux, from your working directory:

mv path/to/file/xxx ./xxx

You would then have to stage the changes resulting from the system move command. You may also try using git mv:

git mv path/to/file/xxx ./xxx

Using git mv should also take care of the staging work for you.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

The previous answers overwrite the file we are checking out. To avoid this we can use git show according to this answer and Jeff Trull's comment to the question.

git show other_branch:path/to/file/xxx > xxx

git show other_branch:path/to/file/xxx outputs the file contents to stdout and > xxx redirects that output to the file xxx instead.

Anton
  • 1,045
  • 1
  • 7
  • 16