How to merge a specific file from another branch in Git?

Tim Mouskhelichvili
Tim Mouskhelichvili
2 minutes to read

When working on a Git repository, by yourself or with other developers, you may need to merge a specific file from another branch. But how do you do it?

This article gives multiple methods of achieving it with detailed steps.

Let's get to it 😎.

git merge specific file

Let's say we have a Git repository with two branches:

  • main
  • feature/a (contains a file called file.js that you want to merge).

Method #1 - Use the patch option

One easy way to merge a specific file from another branch in Git is to use the checkout command with the patch flag.

Here are the steps to follow:

1. Switch to the main branch.

bashgit checkout main

2. Merge the specific file.

bashgit checkout --patch feature/a file.js

3. You will see an interactive prompt, with your changes and a message like so:

bashApply this hunk to index and worktree [y,n,q,a,d,e,?]?

4. Press y to complete the merge process.

Method #2 - Copy the file.

One more option to merge a specific file into another branch is to copy it using the checkout command.

Here are the steps to follow:

1. Switch to the main branch.

bashgit checkout main

2. Copy the specific file to the main branch.

bashgit checkout feature/a file.js

3. Resolve the conflicts (if needed).

Method #3 - Cherry pick the file.

Finally, you can use the cherry-pick option to merge a specific file into another branch.

⚠️ This method only works if you have one file per commit. ⚠️

Here are the steps to follow:

1. Switch to the main branch.

bashgit checkout main

2. Find the commit's hash that contains the file you want to merge.

bashgit log

3. Cherry-pick the file.

bashgit cherry-pick {HASH}

Final thought

As you can see, it is simple and easy to merge a specific file into another branch in Git.

Most of the time, the patch option will do the trick for you.

git merge specific file

Here are some other Git tutorials for you to enjoy:

Comments (0)
Reply to: