DEV Community

Alex Ruzenhack
Alex Ruzenhack

Posted on

Git merge specific file from another branch

There are two teams working on the same project and they realize a common problem that was already resolved by one side, but the status of work in each branch is in progress and to make a merge can be unsafe.

How to solve this problem?

There is a safe solution: merge a specific file from another branch. And there is the steps:

$ git checkout <another-branch> <path-to-file> [<one-more-file> ...]
$ git status
$ git commit -m "'Merge' specific file from '<another-branch>'"

That's it!

Here is a more detailed approach.

Top comments (11)

Collapse
 
marvinkweyu profile image
Marvin

What this does is replace a file on a branch with the file from the other branch.The actual solution would look like this:

Say I had a file1.txt in branch B I wanted to merge with a file1.txt in branch A.

git checkout A

git checkout --patch B file1.txt
Enter fullscreen mode Exit fullscreen mode

1.First, get yourself to branch A(Where you want to do the merge).
2.Patch with the file from branch B.

If your file1.txt does not exist in branch A , leave out the option --patch.
Note that once this command is run, you can accept options that will be provided in the terminal. You can choose to accept with the y or regect with n and so on

Collapse
 
m3ck0 profile image
Giorgi Jambazishvili

Thanks, this saved my googling time :)

Collapse
 
marvinkweyu profile image
Marvin

Glad I could help

Collapse
 
himito profile image
Jaime Arias Almeida

Thanks a lot !

Collapse
 
lejma profile image
lejma

this works slightly differently than advertised, it does not "merge" a specific file, it "checks out" a specific file, when you have a different version of your file and you actually want to merge those it doesnt work, git checkout branch filename just overrides yours without any prompt to merge differences

Collapse
 
pr00thmatic profile image
pr00thmatic

this doesn't actually merge the file... it just overwrites it with the version in the another branch!!

Collapse
 
marvinkweyu profile image
Marvin

You're actually right

Collapse
 
drbragg profile image
Drew Bragg • Edited

Was literally JUST talking about this today, thanks!

Collapse
 
bodhihaven profile image
Jonathan Martin

One of those things I learn today and need to use tomorrow.

Collapse
 
sgelbart profile image
Sabrina Leggett

I could only get this to work with individual files for some reason

Collapse
 
nirajkvinit profile image
Niraj Kumar

This does not merge the files, instead, this command will overwrite the current file with the incoming file. You should include -p flag