Move Code Changes Between Branches With Git Patch Files

Posted on Dec 5, 2024

With patch files Git provides an easy-to-use way to move code changes between branches.

A patch file contains information about the changed lines in a comparable way like it’s shown when doing a git diff.

Here’s how to use it.

Move code from branch A to branch B

Move code from branch A to branch B, where branch B does not depend on branch A.

  1. On branch A create patch file:
git format-patch -1 COMMIT_ID
  1. On branch B apply the created patch file:
git apply PATCH_FILE
  1. Interactively choose hunks to add:
git add -p

If branch B depends on branch A and you want to move a change to branch B, then you can do the same. But you need to remove the conflicts.

By the way: The same works for moving changes between repositories.

Closer view at format-patch

This creates a patch file for COMMIT_ID:

git format-patch -1 COMMIT_ID

For the latest commit on the current branch (= HEAD) the following works, too:

git format-patch -1 HEAD

This creates two patch files for the last two commits beginning on COMMIT_ID and including COMMIT_ID:

git format-patch -2 COMMIT_ID

This creates two patch files for the last two commits on the current branch (= HEAD):

git format-patch HEAD~2

This combines the two latest commits into one:

git format-patch -2 HEAD --stdout > last-two.patch

As before it can be used with a specific commits:

git format-patch -2 COMMIT_ID --stdout > last-two.patch

Conclusion

This post showed just a small subset of the possibilities of git patchsets. I can recommend to work with them to have a clean codebase and use it for moving code parts around.

Want to know more?

Keep on reading and choose one of the related articles. You can also check the home page for my latest thoughts, notes and articles.