[git] How can I selectively merge or pick changes from another branch in Git?

I'm using Git on a new project that has two parallel -- but currently experimental -- development branches:

  • master: import of existing codebase plus a few modifications that I'm generally sure of
  • exp1: experimental branch #1
  • exp2: experimental branch #2

exp1 and exp2 represent two very different architectural approaches. Until I get further along I have no way of knowing which one (if either) will work. As I make progress in one branch I sometimes have edits that would be useful in the other branch and would like to merge just those.

What is the best way to merge selective changes from one development branch to another while leaving behind everything else?

Approaches I've considered:

  1. git merge --no-commit followed by manual unstaging of a large number of edits that I don't want to make common between the branches.

  2. Manual copying of common files into a temporary directory followed by git checkout to move to the other branch and then more manual copying out of the temporary directory into the working tree.

  3. A variation on the above. Abandon the exp branches for now and use two additional local repositories for experimentation. This makes the manual copying of files much more straightforward.

All three of these approaches seem tedious and error-prone. I'm hoping there is a better approach; something akin to a filter path parameter that would make git-merge more selective.

This question is related to git git-merge git-cherry-pick git-patch

The answer is


This is my workflow for merging selective files.

# Make a new branch (this will be temporary)
git checkout -b newbranch

# Grab the changes
git merge --no-commit  featurebranch

# Unstage those changes
git reset HEAD
(You can now see the files from the merge are unstaged)

# Now you can chose which files are to be merged.
git add -p

# Remember to "git add" any new files you wish to keep
git commit

The easiest way is to set your repository to the branch you want to merge with, and then run

git checkout [branch with file] [path to file you would like to merge]

If you run

git status

you will see the file already staged...

Then run

git commit -m "Merge changes on '[branch]' to [file]"

Simple.


Here is how you can replace Myclass.java file in master branch with Myclass.java in feature1 branch. It will work even if Myclass.java doesn't exist on master.

git checkout master
git checkout feature1 Myclass.java

Note this will overwrite - not merge - and ignore local changes in the master branch rather.


1800 INFORMATION's answer is completely correct. As someone new to Git, though, "use git cherry-pick" wasn't enough for me to figure this out without a bit more digging on the Internet, so I thought I'd post a more detailed guide in case anyone else is in a similar boat.

My use case was wanting to selectively pull changes from someone else's GitHub branch into my own. If you already have a local branch with the changes, you only need to do steps 2 and 5-7.

  1. Create (if not created) a local branch with the changes you want to bring in.

    $ git branch mybranch <base branch>

  2. Switch into it.

    $ git checkout mybranch

  3. Pull down the changes you want from the other person's account. If you haven't already, you'll want to add them as a remote.

    $ git remote add repos-w-changes <git url>

  4. Pull down everything from their branch.

    $ git pull repos-w-changes branch-i-want

  5. View the commit logs to see which changes you want:

    $ git log

  6. Switch back to the branch you want to pull the changes into.

    $ git checkout originalbranch

  7. Cherry pick your commits, one by one, with the hashes.

    $ git cherry-pick -x hash-of-commit


It is not exactly what you were looking for, but it was useful to me:

git checkout -p <branch> -- <paths> ...

It is a mix of some answers.


I don't like the above approaches. Using cherry-pick is great for picking a single change, but it is a pain if you want to bring in all the changes except for some bad ones. Here is my approach.

There is no --interactive argument you can pass to git merge.

Here is the alternative:

You have some changes in branch 'feature' and you want to bring some but not all of them over to 'master' in a not sloppy way (i.e. you don't want to cherry pick and commit each one)

git checkout feature
git checkout -b temp
git rebase -i master

# Above will drop you in an editor and pick the changes you want ala:
pick 7266df7 First change
pick 1b3f7df Another change
pick 5bbf56f Last change

# Rebase b44c147..5bbf56f onto b44c147
#
# Commands:
# pick = use commit
# edit = use commit, but stop for amending
# squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

git checkout master
git pull . temp
git branch -d temp

So just wrap that in a shell script, change master into $to and change feature into $from and you are good to go:

#!/bin/bash
# git-interactive-merge
from=$1
to=$2
git checkout $from
git checkout -b ${from}_tmp
git rebase -i $to
# Above will drop you in an editor and pick the changes you want
git checkout $to
git pull . ${from}_tmp
git branch -d ${from}_tmp

If you only need to merge a particular directory and leave everything else intact and yet preserve history, you could possibly try this... create a new target-branch off of the master before you experiment.

The steps below assume you have two branches target-branch and source-branch, and the directory dir-to-merge that you want to merge is in the source-branch. Also assume you have other directories like dir-to-retain in the target that you don't want to change and retain history. Also, assumes there are merge conflicts in the dir-to-merge.

git checkout target-branch
git merge --no-ff --no-commit -X theirs source-branch
# the option "-X theirs", will pick theirs when there is a conflict. 
# the options "--no--ff --no-commit" prevent a commit after a merge, and give you an opportunity to fix other directories you want to retain, before you commit this merge.

# the above, would have messed up the other directories that you want to retain.
# so you need to reset them for every directory that you want to retain.
git reset HEAD dir-to-retain
# verify everything and commit.

For me, git reset --soft branch is the easiest way to selectively pick the changes from another branch, since, this command puts in my working tree, all the diff changes, and I can easily pick or revert which one I need.

In this way, I have full control over the committed files.


Here is how you can replace Myclass.java file in master branch with Myclass.java in feature1 branch. It will work even if Myclass.java doesn't exist on master.

git checkout master
git checkout feature1 Myclass.java

Note this will overwrite - not merge - and ignore local changes in the master branch rather.


I found this post to contain the simplest answer. Merely do:

git checkout <branch from which you want files> <file paths>

Example

Pulling .gitignore file from branchB into current branch:

git checkout branchB .gitignore

See the post for more information.


When only a few files have changed between the current commits of the two branches, I manually merge the changes by going through the different files.

git difftool <branch-1>..<branch-2>

see also https://sites.google.com/site/icusite/setup/git-difftool


The simple way, to actually merge specific files from two branches, not just replace specific files with ones from another branch.

Step one: Diff the branches

git diff branch_b > my_patch_file.patch

Creates a patch file of the difference between the current branch and branch_b

Step two: Apply the patch on files matching a pattern

git apply -p1 --include=pattern/matching/the/path/to/file/or/folder my_patch_file.patch

Useful notes on the options

You can use * as a wildcard in the include pattern.

Slashes don't need to be escaped.

Also, you could use --exclude instead and apply it to everything except the files matching the pattern, or reverse the patch with -R

The -p1 option is a holdover from the *Unix patch command and the fact that the patch file's contents prepend each file name with a/ or b/ (or more depending on how the patch file was generated) which you need to strip, so that it can figure out the real file to the path to the file the patch needs to be applied to.

Check out the man page for git-apply for more options.

Step three: there is no step three

Obviously you'd want to commit your changes, but who's to say you don't have some other related tweaks you want to do before making your commit.


Here's how you can get history to follow just a couple of files from another branch with a minimum of fuss, even if a more "simple" merge would have brought over a lot more changes that you don't want.

First, you'll take the unusual step of declaring in advance that what you're about to commit is a merge, without Git doing anything at all to the files in your working directory:

git merge --no-ff --no-commit -s ours branchname1

... where "branchname" is whatever you claim to be merging from. If you were to commit right away, it would make no changes, but it would still show ancestry from the other branch. You can add more branches, tags, etc. to the command line if you need to, as well. At this point though, there are no changes to commit, so get the files from the other revisions, next.

git checkout branchname1 -- file1 file2 etc.

If you were merging from more than one other branch, repeat as needed.

git checkout branchname2 -- file3 file4 etc.

Now the files from the other branch are in the index, ready to be committed, with history.

git commit

And you'll have a lot of explaining to do in that commit message.

Please note though, in case it wasn't clear, that this is a messed up thing to do. It is not in the spirit of what a "branch" is for, and cherry-pick is a more honest way to do what you'd be doing, here. If you wanted to do another "merge" for other files on the same branch that you didn't bring over last time, it will stop you with an "already up to date" message. It's a symptom of not branching when we should have, in that the "from" branch should be more than one different branch.


It's strange that git still does not have such a convenient tool "out of the box". I use it heavily when update some old version branch (which still has a lot of software users) by just some bugfixes from the current version branch. In this case it is often needed to quickly get just some lines of code from the file in trunk, ignoring a lot of other changes (that are not supposed to go into the old version)... And of course interactive three-way merge is needed in this case, git checkout --patch <branch> <file path> is not usable for this selective merge purpose.

You can do it easily:

Just add this line to [alias] section in your global .gitconfig or local .git/config file:

[alias]
    mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs; git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base; /C/BCompare3/BCompare.exe $2.theirs $2 $2.base $2; rm -f $2.theirs; rm -f $2.base;' -"

It implies you use Beyond Compare. Just change to software of your choice if needed. Or you can change it to three-way auto-merge if you don't need the interactive selective merging:

[alias]
    mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs; git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base; git merge-file $2 $2.base $2.theirs; rm -f $2.theirs; rm -f $2.base;' -"

Then use like this:

git mergetool-file <source branch> <file path>

This will give you the true selective tree-way merge opportunity of just any file in other branch.


1800 INFORMATION's answer is completely correct. As someone new to Git, though, "use git cherry-pick" wasn't enough for me to figure this out without a bit more digging on the Internet, so I thought I'd post a more detailed guide in case anyone else is in a similar boat.

My use case was wanting to selectively pull changes from someone else's GitHub branch into my own. If you already have a local branch with the changes, you only need to do steps 2 and 5-7.

  1. Create (if not created) a local branch with the changes you want to bring in.

    $ git branch mybranch <base branch>

  2. Switch into it.

    $ git checkout mybranch

  3. Pull down the changes you want from the other person's account. If you haven't already, you'll want to add them as a remote.

    $ git remote add repos-w-changes <git url>

  4. Pull down everything from their branch.

    $ git pull repos-w-changes branch-i-want

  5. View the commit logs to see which changes you want:

    $ git log

  6. Switch back to the branch you want to pull the changes into.

    $ git checkout originalbranch

  7. Cherry pick your commits, one by one, with the hashes.

    $ git cherry-pick -x hash-of-commit


I would do a

git diff commit1..commit2 filepattern | git-apply --index && git commit

This way you can limit the range of commits for a filepattern from a branch.

It is stolen from Re: How to pull only a few files from one branch to another?


If you don't have too many files that have changed, this will leave you with no extra commits.

1. Duplicate branch temporarily
$ git checkout -b temp_branch

2. Reset to last wanted commit
$ git reset --hard HEAD~n, where n is the number of commits you need to go back

3. Checkout each file from original branch
$ git checkout origin/original_branch filename.ext

Now you can commit and force push (to overwrite remote), if needed.


I like the previous 'git-interactive-merge' answer, but there's one easier. Let Git do this for you using a rebase combination of interactive and onto:

      A---C1---o---C2---o---o feature
     /
----o---o---o---o master

So the case is you want C1 and C2 from the 'feature' branch (branch point 'A'), but none of the rest for now.

# git branch temp feature
# git checkout master
# git rebase -i --onto HEAD A temp

Which, as in the previous answer, drops you in to the interactive editor where you select the 'pick' lines for C1 and C2 (as above). Save and quit, and then it will proceed with the rebase and give you branch 'temp' and also HEAD at master + C1 + C2:

      A---C1---o---C2---o---o feature
     /
----o---o---o---o-master--C1---C2 [HEAD, temp]

Then you can just update master to HEAD and delete the temp branch and you're good to go:

# git branch -f master HEAD
# git branch -d temp

I would do a

git diff commit1..commit2 filepattern | git-apply --index && git commit

This way you can limit the range of commits for a filepattern from a branch.

It is stolen from Re: How to pull only a few files from one branch to another?


Here's how you can get history to follow just a couple of files from another branch with a minimum of fuss, even if a more "simple" merge would have brought over a lot more changes that you don't want.

First, you'll take the unusual step of declaring in advance that what you're about to commit is a merge, without Git doing anything at all to the files in your working directory:

git merge --no-ff --no-commit -s ours branchname1

... where "branchname" is whatever you claim to be merging from. If you were to commit right away, it would make no changes, but it would still show ancestry from the other branch. You can add more branches, tags, etc. to the command line if you need to, as well. At this point though, there are no changes to commit, so get the files from the other revisions, next.

git checkout branchname1 -- file1 file2 etc.

If you were merging from more than one other branch, repeat as needed.

git checkout branchname2 -- file3 file4 etc.

Now the files from the other branch are in the index, ready to be committed, with history.

git commit

And you'll have a lot of explaining to do in that commit message.

Please note though, in case it wasn't clear, that this is a messed up thing to do. It is not in the spirit of what a "branch" is for, and cherry-pick is a more honest way to do what you'd be doing, here. If you wanted to do another "merge" for other files on the same branch that you didn't bring over last time, it will stop you with an "already up to date" message. It's a symptom of not branching when we should have, in that the "from" branch should be more than one different branch.


I had the exact same problem as mentioned by you above. But I found this Git blog clearer in explaining the answer.

Command from the above link:

# You are in the branch you want to merge to
git checkout <branch_you_want_to_merge_from> <file_paths...>

You can use read-tree to read or merge a given remote tree into the current index, for example:

git remote add foo [email protected]/foo.git
git fetch foo
git read-tree --prefix=my-folder/ -u foo/master:trunk/their-folder

To perform the merge, use -m instead.

See also: How do I merge a sub directory in Git?


The easiest way is to set your repository to the branch you want to merge with, and then run

git checkout [branch with file] [path to file you would like to merge]

If you run

git status

you will see the file already staged...

Then run

git commit -m "Merge changes on '[branch]' to [file]"

Simple.


For me, git reset --soft branch is the easiest way to selectively pick the changes from another branch, since, this command puts in my working tree, all the diff changes, and I can easily pick or revert which one I need.

In this way, I have full control over the committed files.


I wrote my own script called 'pmerge' to partially merge directories. It's a work in progress and I'm still learning both Git and Bash scripting.

This command uses git merge --no-commit and then unapplies changes that don't match the path provided.

Usage: git pmerge branch path
Example: git merge develop src/

I haven't tested it extensively. The working directory should be free of any uncommitted changes and untracked files.

#!/bin/bash

E_BADARGS=65

if [ $# -ne 2 ]
then
    echo "Usage: `basename $0` branch path"
    exit $E_BADARGS
fi

git merge $1 --no-commit
IFS=$'\n'

# List of changes due to merge | replace nulls with newlines | strip lines to just filenames | ensure lines are unique
for f in $(git status --porcelain -z -uno | tr '\000' '\n' | sed -e 's/^[[:graph:]][[:space:]]\{1,\}//' | uniq); do
    [[ $f == $2* ]] && continue
    if git reset $f >/dev/null 2>&1; then
        # Reset failed... file was previously unversioned
        echo Deleting $f
        rm $f
    else
        echo Reverting $f
        git checkout -- $f >/dev/null 2>&1
    fi
done
unset IFS

While some of these answers are pretty good, I feel like none actually answered the OP's original constraint: selecting particular files from particular branches. This solution does that, but it may be tedious if there are many files.

Let’s say you have the master, exp1, and exp2 branches. You want to merge one file from each of the experimental branches into master. I would do something like this:

git checkout master
git checkout exp1 path/to/file_a
git checkout exp2 path/to/file_b

# Save these files as a stash
git stash

# Merge stash with master
git merge stash

This will give you in-file diffs for each of the files you want. Nothing more. Nothing less. It's useful you have radically different file changes between versions --in my case, changing an application from Ruby on Rails 2 to Ruby on Rails 3.

This will merge files, but it does a smart merge. I wasn't able to figure out how to use this method to get in-file diff information (maybe it still will for extreme differences. Annoying small things like whitespace get merged back in unless you use the -s recursive -X ignore-all-space option)


The simple way, to actually merge specific files from two branches, not just replace specific files with ones from another branch.

Step one: Diff the branches

git diff branch_b > my_patch_file.patch

Creates a patch file of the difference between the current branch and branch_b

Step two: Apply the patch on files matching a pattern

git apply -p1 --include=pattern/matching/the/path/to/file/or/folder my_patch_file.patch

Useful notes on the options

You can use * as a wildcard in the include pattern.

Slashes don't need to be escaped.

Also, you could use --exclude instead and apply it to everything except the files matching the pattern, or reverse the patch with -R

The -p1 option is a holdover from the *Unix patch command and the fact that the patch file's contents prepend each file name with a/ or b/ (or more depending on how the patch file was generated) which you need to strip, so that it can figure out the real file to the path to the file the patch needs to be applied to.

Check out the man page for git-apply for more options.

Step three: there is no step three

Obviously you'd want to commit your changes, but who's to say you don't have some other related tweaks you want to do before making your commit.


I don't like the above approaches. Using cherry-pick is great for picking a single change, but it is a pain if you want to bring in all the changes except for some bad ones. Here is my approach.

There is no --interactive argument you can pass to git merge.

Here is the alternative:

You have some changes in branch 'feature' and you want to bring some but not all of them over to 'master' in a not sloppy way (i.e. you don't want to cherry pick and commit each one)

git checkout feature
git checkout -b temp
git rebase -i master

# Above will drop you in an editor and pick the changes you want ala:
pick 7266df7 First change
pick 1b3f7df Another change
pick 5bbf56f Last change

# Rebase b44c147..5bbf56f onto b44c147
#
# Commands:
# pick = use commit
# edit = use commit, but stop for amending
# squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

git checkout master
git pull . temp
git branch -d temp

So just wrap that in a shell script, change master into $to and change feature into $from and you are good to go:

#!/bin/bash
# git-interactive-merge
from=$1
to=$2
git checkout $from
git checkout -b ${from}_tmp
git rebase -i $to
# Above will drop you in an editor and pick the changes you want
git checkout $to
git pull . ${from}_tmp
git branch -d ${from}_tmp

If you don't have too many files that have changed, this will leave you with no extra commits.

1. Duplicate branch temporarily
$ git checkout -b temp_branch

2. Reset to last wanted commit
$ git reset --hard HEAD~n, where n is the number of commits you need to go back

3. Checkout each file from original branch
$ git checkout origin/original_branch filename.ext

Now you can commit and force push (to overwrite remote), if needed.


To selectively merge files from one branch into another branch, run

git merge --no-ff --no-commit branchX

where branchX is the branch you want to merge from into the current branch.

The --no-commit option will stage the files that have been merged by Git without actually committing them. This will give you the opportunity to modify the merged files however you want to and then commit them yourself.

Depending on how you want to merge files, there are four cases:

1) You want a true merge.

In this case, you accept the merged files the way Git merged them automatically and then commit them.

2) There are some files you don't want to merge.

For example, you want to retain the version in the current branch and ignore the version in the branch you are merging from.

To select the version in the current branch, run:

git checkout HEAD file1

This will retrieve the version of file1 in the current branch and overwrite the file1 automerged by Git.

3) If you want the version in branchX (and not a true merge).

Run:

git checkout branchX file1

This will retrieve the version of file1 in branchX and overwrite file1 auto-merged by Git.

4) The last case is if you want to select only specific merges in file1.

In this case, you can edit the modified file1 directly, update it to whatever you'd want the version of file1 to become, and then commit.

If Git cannot merge a file automatically, it will report the file as "unmerged" and produce a copy where you will need to resolve the conflicts manually.



To explain further with an example, let's say you want to merge branchX into the current branch:

git merge --no-ff --no-commit branchX

You then run the git status command to view the status of modified files.

For example:

git status

# On branch master
# Changes to be committed:
#
#       modified:   file1
#       modified:   file2
#       modified:   file3
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#       both modified:      file4
#

Where file1, file2, and file3 are the files git have successfully auto-merged.

What this means is that changes in the master and branchX for all those three files have been combined together without any conflicts.

You can inspect how the merge was done by running the git diff --cached;

git diff --cached file1
git diff --cached file2
git diff --cached file3

If you find some merge undesirable then you can

  1. edit the file directly
  2. save
  3. git commit

If you don't want to merge file1 and want to retain the version in the current branch

Run

git checkout HEAD file1

If you don't want to merge file2 and only want the version in branchX

Run

git checkout branchX file2

If you want file3 to be merged automatically, don't do anything.

Git has already merged it at this point.


file4 above is a failed merge by Git. This means there are changes in both branches that occur on the same line. This is where you will need to resolve the conflicts manually. You can discard the merged done by editing the file directly or running the checkout command for the version in the branch you want file4 to become.


Finally, don't forget to git commit.


I wrote my own script called 'pmerge' to partially merge directories. It's a work in progress and I'm still learning both Git and Bash scripting.

This command uses git merge --no-commit and then unapplies changes that don't match the path provided.

Usage: git pmerge branch path
Example: git merge develop src/

I haven't tested it extensively. The working directory should be free of any uncommitted changes and untracked files.

#!/bin/bash

E_BADARGS=65

if [ $# -ne 2 ]
then
    echo "Usage: `basename $0` branch path"
    exit $E_BADARGS
fi

git merge $1 --no-commit
IFS=$'\n'

# List of changes due to merge | replace nulls with newlines | strip lines to just filenames | ensure lines are unique
for f in $(git status --porcelain -z -uno | tr '\000' '\n' | sed -e 's/^[[:graph:]][[:space:]]\{1,\}//' | uniq); do
    [[ $f == $2* ]] && continue
    if git reset $f >/dev/null 2>&1; then
        # Reset failed... file was previously unversioned
        echo Deleting $f
        rm $f
    else
        echo Reverting $f
        git checkout -- $f >/dev/null 2>&1
    fi
done
unset IFS

I had the exact same problem as mentioned by you above. But I found this Git blog clearer in explaining the answer.

Command from the above link:

# You are in the branch you want to merge to
git checkout <branch_you_want_to_merge_from> <file_paths...>

While some of these answers are pretty good, I feel like none actually answered the OP's original constraint: selecting particular files from particular branches. This solution does that, but it may be tedious if there are many files.

Let’s say you have the master, exp1, and exp2 branches. You want to merge one file from each of the experimental branches into master. I would do something like this:

git checkout master
git checkout exp1 path/to/file_a
git checkout exp2 path/to/file_b

# Save these files as a stash
git stash

# Merge stash with master
git merge stash

This will give you in-file diffs for each of the files you want. Nothing more. Nothing less. It's useful you have radically different file changes between versions --in my case, changing an application from Ruby on Rails 2 to Ruby on Rails 3.

This will merge files, but it does a smart merge. I wasn't able to figure out how to use this method to get in-file diff information (maybe it still will for extreme differences. Annoying small things like whitespace get merged back in unless you use the -s recursive -X ignore-all-space option)


To selectively merge files from one branch into another branch, run

git merge --no-ff --no-commit branchX

where branchX is the branch you want to merge from into the current branch.

The --no-commit option will stage the files that have been merged by Git without actually committing them. This will give you the opportunity to modify the merged files however you want to and then commit them yourself.

Depending on how you want to merge files, there are four cases:

1) You want a true merge.

In this case, you accept the merged files the way Git merged them automatically and then commit them.

2) There are some files you don't want to merge.

For example, you want to retain the version in the current branch and ignore the version in the branch you are merging from.

To select the version in the current branch, run:

git checkout HEAD file1

This will retrieve the version of file1 in the current branch and overwrite the file1 automerged by Git.

3) If you want the version in branchX (and not a true merge).

Run:

git checkout branchX file1

This will retrieve the version of file1 in branchX and overwrite file1 auto-merged by Git.

4) The last case is if you want to select only specific merges in file1.

In this case, you can edit the modified file1 directly, update it to whatever you'd want the version of file1 to become, and then commit.

If Git cannot merge a file automatically, it will report the file as "unmerged" and produce a copy where you will need to resolve the conflicts manually.



To explain further with an example, let's say you want to merge branchX into the current branch:

git merge --no-ff --no-commit branchX

You then run the git status command to view the status of modified files.

For example:

git status

# On branch master
# Changes to be committed:
#
#       modified:   file1
#       modified:   file2
#       modified:   file3
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#       both modified:      file4
#

Where file1, file2, and file3 are the files git have successfully auto-merged.

What this means is that changes in the master and branchX for all those three files have been combined together without any conflicts.

You can inspect how the merge was done by running the git diff --cached;

git diff --cached file1
git diff --cached file2
git diff --cached file3

If you find some merge undesirable then you can

  1. edit the file directly
  2. save
  3. git commit

If you don't want to merge file1 and want to retain the version in the current branch

Run

git checkout HEAD file1

If you don't want to merge file2 and only want the version in branchX

Run

git checkout branchX file2

If you want file3 to be merged automatically, don't do anything.

Git has already merged it at this point.


file4 above is a failed merge by Git. This means there are changes in both branches that occur on the same line. This is where you will need to resolve the conflicts manually. You can discard the merged done by editing the file directly or running the checkout command for the version in the branch you want file4 to become.


Finally, don't forget to git commit.


You can use read-tree to read or merge a given remote tree into the current index, for example:

git remote add foo [email protected]/foo.git
git fetch foo
git read-tree --prefix=my-folder/ -u foo/master:trunk/their-folder

To perform the merge, use -m instead.

See also: How do I merge a sub directory in Git?


I had the exact same problem as mentioned by you above. But I found this clearer in explaining the answer.

Summary:

  • Check out the path(s) from the branch you want to merge,

     $ git checkout source_branch -- <paths>...
    
    Hint: It also works without `--` like seen in the linked post.
    
  • or to selectively merge hunks

     $ git checkout -p source_branch -- <paths>...
    

Alternatively, use reset and then add with the option -p,

    $ git reset <paths>...
    $ git add -p <paths>...
  • Finally commit

     $ git commit -m "'Merge' these changes"
    

I like the previous 'git-interactive-merge' answer, but there's one easier. Let Git do this for you using a rebase combination of interactive and onto:

      A---C1---o---C2---o---o feature
     /
----o---o---o---o master

So the case is you want C1 and C2 from the 'feature' branch (branch point 'A'), but none of the rest for now.

# git branch temp feature
# git checkout master
# git rebase -i --onto HEAD A temp

Which, as in the previous answer, drops you in to the interactive editor where you select the 'pick' lines for C1 and C2 (as above). Save and quit, and then it will proceed with the rebase and give you branch 'temp' and also HEAD at master + C1 + C2:

      A---C1---o---C2---o---o feature
     /
----o---o---o---o-master--C1---C2 [HEAD, temp]

Then you can just update master to HEAD and delete the temp branch and you're good to go:

# git branch -f master HEAD
# git branch -d temp

A simple approach for selective merging/committing by file:

git checkout dstBranch
git merge srcBranch

// Make changes, including resolving conflicts to single files
git add singleFile1 singleFile2
git commit -m "message specific to a few files"
git reset --hard # Blow away uncommitted changes

There is another way to go:

git checkout -p

It is a mix between git checkout and git add -p and might quite be exactly what you are looking for:

   -p, --patch
       Interactively select hunks in the difference between the <tree-ish>
       (or the index, if unspecified) and the working tree. The chosen
       hunks are then applied in reverse to the working tree (and if a
       <tree-ish> was specified, the index).

       This means that you can use git checkout -p to selectively discard
       edits from your current working tree. See the “Interactive Mode”
       section of git-add(1) to learn how to operate the --patch mode.

I found this post to contain the simplest answer. Merely do:

git checkout <branch from which you want files> <file paths>

Example

Pulling .gitignore file from branchB into current branch:

git checkout branchB .gitignore

See the post for more information.


A simple approach for selective merging/committing by file:

git checkout dstBranch
git merge srcBranch

// Make changes, including resolving conflicts to single files
git add singleFile1 singleFile2
git commit -m "message specific to a few files"
git reset --hard # Blow away uncommitted changes

If you only need to merge a particular directory and leave everything else intact and yet preserve history, you could possibly try this... create a new target-branch off of the master before you experiment.

The steps below assume you have two branches target-branch and source-branch, and the directory dir-to-merge that you want to merge is in the source-branch. Also assume you have other directories like dir-to-retain in the target that you don't want to change and retain history. Also, assumes there are merge conflicts in the dir-to-merge.

git checkout target-branch
git merge --no-ff --no-commit -X theirs source-branch
# the option "-X theirs", will pick theirs when there is a conflict. 
# the options "--no--ff --no-commit" prevent a commit after a merge, and give you an opportunity to fix other directories you want to retain, before you commit this merge.

# the above, would have messed up the other directories that you want to retain.
# so you need to reset them for every directory that you want to retain.
git reset HEAD dir-to-retain
# verify everything and commit.

There is another way to go:

git checkout -p

It is a mix between git checkout and git add -p and might quite be exactly what you are looking for:

   -p, --patch
       Interactively select hunks in the difference between the <tree-ish>
       (or the index, if unspecified) and the working tree. The chosen
       hunks are then applied in reverse to the working tree (and if a
       <tree-ish> was specified, the index).

       This means that you can use git checkout -p to selectively discard
       edits from your current working tree. See the “Interactive Mode”
       section of git-add(1) to learn how to operate the --patch mode.

It's strange that git still does not have such a convenient tool "out of the box". I use it heavily when update some old version branch (which still has a lot of software users) by just some bugfixes from the current version branch. In this case it is often needed to quickly get just some lines of code from the file in trunk, ignoring a lot of other changes (that are not supposed to go into the old version)... And of course interactive three-way merge is needed in this case, git checkout --patch <branch> <file path> is not usable for this selective merge purpose.

You can do it easily:

Just add this line to [alias] section in your global .gitconfig or local .git/config file:

[alias]
    mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs; git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base; /C/BCompare3/BCompare.exe $2.theirs $2 $2.base $2; rm -f $2.theirs; rm -f $2.base;' -"

It implies you use Beyond Compare. Just change to software of your choice if needed. Or you can change it to three-way auto-merge if you don't need the interactive selective merging:

[alias]
    mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs; git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base; git merge-file $2 $2.base $2.theirs; rm -f $2.theirs; rm -f $2.base;' -"

Then use like this:

git mergetool-file <source branch> <file path>

This will give you the true selective tree-way merge opportunity of just any file in other branch.


It is not exactly what you were looking for, but it was useful to me:

git checkout -p <branch> -- <paths> ...

It is a mix of some answers.


I had the exact same problem as mentioned by you above. But I found this clearer in explaining the answer.

Summary:

  • Check out the path(s) from the branch you want to merge,

     $ git checkout source_branch -- <paths>...
    
    Hint: It also works without `--` like seen in the linked post.
    
  • or to selectively merge hunks

     $ git checkout -p source_branch -- <paths>...
    

Alternatively, use reset and then add with the option -p,

    $ git reset <paths>...
    $ git add -p <paths>...
  • Finally commit

     $ git commit -m "'Merge' these changes"
    

When only a few files have changed between the current commits of the two branches, I manually merge the changes by going through the different files.

git difftool <branch-1>..<branch-2>

see also https://sites.google.com/site/icusite/setup/git-difftool


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to git-merge

Abort a Git Merge Git pull - Please move or remove them before you can merge Git: How configure KDiff3 as merge tool and diff tool Git: How to pull a single file from a server repository in Git? How to resolve git error: "Updates were rejected because the tip of your current branch is behind" error: Your local changes to the following files would be overwritten by checkout Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch How to merge specific files from Git branches git remove merge commit from history The following untracked working tree files would be overwritten by merge, but I don't care

Examples related to git-cherry-pick

Git Cherry-Pick and Conflicts Abort a git cherry-pick? What does cherry-picking a commit with Git mean? Merge up to a specific commit How to cherry pick from 1 branch to another How to cherry pick a range of commits and merge into another branch? Partly cherry-picking a commit with Git How can I selectively merge or pick changes from another branch in Git?

Examples related to git-patch

Create a git patch from the uncommitted changes in the current working directory How can I selectively merge or pick changes from another branch in Git?