gitdiffgit-diffgit-apply

How to prepare and apply multiple patches for the last N commits in git


I need to create a patch file for the last N commits and apply them as separate commits to another branch. For N=3 I assume I have to do this:

git diff HEAD~3 HEAD~2 >> diff1
git diff HEAD~2 HEAD~1 >> diff2
git diff HEAD~1 HEAD >> diff3

and then apply them on another branch respectively:

git apply diff1
(push)
git apply diff2
(push)
git apply diff3

Is there any shorter way to do this?


Solution

  • This can be done with git format-patch and git am, respectively. From your example, try:

    git format-patch HEAD~3
    

    This will generate files 0001-commit-foo.patch, 0002-commit-bar.patch, 0003-commit-baz.patch. Then you can copy them to another repo and use git am to apply them:

    git am *.patch
    

    This will preserve the commits as you made them in the previous tree including commit messages, SHAs, and timestamps.