3

I created a feature branch from the master branch, than (did some work and) had to delete many files on this branch. Now, I would like to merge the changes back into master, but not lose the files on master that I removed on the feature branch.

Here is, in short, what I did:

(master)> git checkout -b feature
# deleted many files
> git checkout master
> git merge ??? # how to merge back without losing files

In other words, when the file exists on the feature branch, than merge it into master. When the file is removed on the feature branch, don't merge the delete operation on master, but keep the file.

How can I do this?

JNevens
  • 11,202
  • 9
  • 46
  • 72

2 Answers2

8

Run

git merge --no-commit feature

to prepare the merge without committing it.

Then inspect the changes (git status) and run:

git checkout master -- file1 file2 ...

where file1, file2 etc. are the files you deleted on the branch and want to keep after merge (they are listed as deleted: in the output of git status.) You can, as well, checkout one file at a time or even get them from another branch if you need.

Then use git add . to stage the files you just checked out and when you are satisfied with the change, run git commit to complete the merge.

If you make a mistake or just want to abort the merge you can run git merge --abort and start over.

The merge operation is in progress until you either successfully complete it using git commit or you abort it using git merge --abort. Some operations are not allowed (or fail) while the merge is not completed.

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Can I run `checkout` multiple times? For example `git checkout master -- file1` followed by `git checkout master -- file2` – JNevens Jan 15 '18 at 19:06
  • @JNevens: yes. Until you `git commit` you are still in the middle of the merge; any and all changes you make to the index will be in the merge result. Note, however, that any changes you make that aren't a product of the inputs result in what people call an ["evil merge" (click to read SO question)](https://stackoverflow.com/q/1461909/1256452), so it may be wise to make a separate commit before or after the merge to insert such changes. – torek Jan 15 '18 at 19:16
0

... had to delete many files on this branch.

If this was done as a separate commit with just deleting those files, you can just revert that/those commits.

hlovdal
  • 26,565
  • 10
  • 94
  • 165