fromthestone
fromthestone

Reputation: 1307

git checkout a single file from another branch and put in different folder

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

Upvotes: 33

Views: 68128

Answers (3)

ontanj
ontanj

Reputation: 1616

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.

Upvotes: 4

Avi Fatal
Avi Fatal

Reputation: 1558

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

Upvotes: 39

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

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.

Upvotes: 4

Related Questions