8

For some reason I want to abandon my branch_A but I have some files just committed in that branch_A. I want to add them to branch_B.

How can I do that?

Paolo
  • 20,112
  • 21
  • 72
  • 113
hidemyname
  • 3,791
  • 7
  • 27
  • 41
  • 2
    Why can't you use merge, rebase, or cherrypick? – Beat Jul 22 '15 at 06:40
  • http://stackoverflow.com/questions/1628563/move-the-most-recent-commits-to-a-new-branch-with-git – Oleksandr Kravchuk Jul 22 '15 at 06:40
  • I added so much garbage that I didn't want to add along with those files. Because I used 'git add -A' and I also committed. So I checkout to the old version and create a new branch. I think if merge it will take me much more time. After all I just have 4 files to add. – hidemyname Jul 22 '15 at 06:46
  • 1
    possible duplicate of [How to git-cherry-pick only changes to certain files?](http://stackoverflow.com/questions/5717026/how-to-git-cherry-pick-only-changes-to-certain-files) – Beat Jul 22 '15 at 06:57
  • @Beat Cherry-picking works with *changes*, not with files. OP does not want to keep the commit information but just the file status, so cherry-picking is not the best way to do this. – poke Jul 22 '15 at 07:17

5 Answers5

21

Switch on the branch B:

git checkout branch_B

Then, checkout the files you want to keep:

git checkout branch_A file1 file2 file3 [...]

At last, commit your changes

git commit -m "Backport changes from branch A for reasons"
blue112
  • 52,634
  • 3
  • 45
  • 54
0

If you're confused on how to execute right commands in console which was proposed above, then you have a lazy, easy option:

1) Copy your files out of your project directory 2) Checkout to your branch_B 3) Replace your copied files with checked-out ones, you can even merge them 4) Commit the change

Novitoll
  • 820
  • 1
  • 9
  • 22
0

git reset HEAD^ will move you one commit back. ie. just before you made the commit onto branch_A. Now switch to branch_B using git checkout branch_B. Then git add the files you want to commit and then git commit them. They will be on branch_B.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
0

Switch on branch_A: git checkout branch_A , use git log and record your commit id. Then switch on branch_B :git checkout branch_B and use git cherry-pick your commit id to move the commit into branch_B.

Jintao Zhang
  • 778
  • 5
  • 9
  • 1
    This is not the correct solution to the question asked. 'git cherry-pick ' moves the entire branch to said commit, not just the selected files. – Sarthchoudhary Jul 25 '22 at 14:45
0

to selectively add changes from another branch

git checkout --patch other_branch file1 file2
Geoff Langenderfer
  • 746
  • 1
  • 9
  • 21