git recover single file that was deleted during a merge

Viewed 16770

I'm currently in branch 'foo'. I just ran git merge master. Only problem is there was a certain file in foo that I wanted to keep. Is there a way to get it back but keep all the other changes from merge master?

2 Answers

Try something like this:

git checkout HEAD -- filename

This will roll your fileback one commit. If you want to go back further to a specific commit, you can use a commit hash or append ^N to the end of the HEAD keyword, e.g. HEAD^2.

I'm not sure how to correct the problem from the current situation, but you may want to look at git merge -s ours. The docs are here.

A workflow would be

  1. Create branch a from master
  2. Do a custom change in branch a that you will not want to merge back into master
  3. Check out master and git merge -s ours a
  4. Check out a and continue working and committing.

Now when you merge with master, the custom changes in step 2 will be ignored.

Related