Git - How to Merge a Single File from a Branch

Sometimes, you may find yourself in a situation when you have to merge just a single file from a branch to the master. An example of this is if you are on a feature branch and you happen to find a bug that you fix and can not wait to finish the feature to deploy the fix.

The better practice would be to switch branches and apply the fix then merge that back into your feature branch. But, we are developers and thus we are rarely that sensible. Here is how to merge a single file.

By the way, this solution was found on StackOverflow here. If you have an account, please head over there and give the answer a upvote if you found this useful.

So I have a simple repository with 2 files: index.html and second_page.html.

Now I have the master branch which you could say is "live" and another branch called amazing_feature_branch. I have made some changes on the latter and committed and pushed them (for the sake of this tutorial, the actual content is irrelevant and I am going to delete the repository when I am done).

Changes

Now say my product manager has come and said to me that although my feature is not finished, I need to put what I have done in index.html onto master. A simple merge won't do as I will also merge what I have done in second_page.html.

Here is what to do:

git checkout master
git checkout --patch amazing_feature_branch index.html

It will show you something like this:

Selected changes

It is asking you if you want to apply these changes to the file. This is actually a very powerful feature as it allows you to not only merge a specific file but you can also merge specific lines.

Let me show you. Let's say I made more than 1 change to the file, so this actually looks like this:

Multiple changes

So you can see there are 2 lines added.

Git is asking if I want to apply this "hunk" to the merge. The simple answer is y and any other hunks will be shown for you to press y to. If you know you want to merge the whole file you can answer with a (as Dmitry points out in the StackOverflow answer comments, git checkout amazing_feature_branch -- index.html will achieve this also and skip this interactive stage).

But what if my answer was "wait a second, I want to apply the first line, but not the second line"? Pressing e, will open up the hunk editor in your favourite text editor like so:

Hunk edit

So I change the second new line to have # instead of + so it is ignored and only the first new line will be applied.

Saving and quitting out of the editor, I can see that there are now unstaged changes to index.html. Doing git diff HEAD demonstrates this:

Git diff

As you can see, only 1 line from all of the changes on my feature branch has actually been merged! I can now commit this and push as I please.

For particularly large hunks, you can use the s option to automatically split it down.

So there you have it: a very powerful, yet very easy to use, feature in Git.


© 2012-2017