Saras Arya
Saras Arya

Reputation: 3112

How to interactively checkout a file from one branch to another in Git

I have two branches in my repo from which I keep editing back and forth and merging changes of one into another. But before merging I like to check what changes are being merged and what is being replaced with what, but there are few files in demo and master which are inherently different from each other and they will be always. That's why 2 different branches. So I tend to use git checkout --patch demo to pull code from the demo branch into master. But this unnecessarily checks all files.
Is it possible that I can interactively check out specific files from 2 branches, instead of checking the whole branch? Very less documentation about the patch method on Git is available. I am hoping someone can clear this up for me.

Upvotes: 7

Views: 8971

Answers (1)

poke
poke

Reputation: 387587

Most Git commands that interact with the working directory allow you to restrict the command to a certain path. This is often done at the end of the command, indicated by a separating --. Many commands also accept a path without that separator but it’s necessary sometimes in order to avoid disambiguity between paths and branch names (or tree-ishes).

So in your case, you can use this as mentioned in the synopsis of the git checkout command:

git checkout [-p|--patch] [<tree-ish>] [--] [<paths>…​]

Running git checkout --patch demo -- path/to/file should work for your situation to restrict the checkout command to only work on that file path, even with the active --patch mode.

Btw., the path/to/file part can also be a path to a directory, which will make the command run for all the files that are in that directory.

Upvotes: 14

Related Questions