A Quick Intro to Git Patch?

Hey! In this post, get a quick glimpse of what is a git patch? How can you create and apply that? What are its use cases, etc? Let’s get started. 🙂

1. What is git ?

Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. And it’s easy to learn and get started. I wrote a tutorial here on git-github when I first learned it, available here: Git Github Tutorial (1)

2. What is a git patch ?

If you have experience with git, then a patch is none other than the git-diff. It simply contains the changes done (previous and new states), or we can say that it contains the patch that fixes or add something upon the previous state. A typical patch looks like this:

diff --git a/file1 b/file1
index 839cf35..18a4bf8 100644
--- a/file1
+++ b/file1
@@ -1,3 +1,3 @@
-This is a line in a file
+This is the changed line1 in a file
This is line2 in the same file

Here, plus ( + ) sign indicates additions and minus ( – ) sign indicates deletions.

3. Why do we need a git patch ?

  1. To send your changes to someone else.
  2. To copy your changes from a git branch to paste it into another branch (in case git merge is not a feasible option).
  3. Just in case you need to save a copy of your changes.

4. Create a patch of specific git commit

To create a patch just redirect your git-diff of a commit to a file. Simple!

git diff 11111commit1111hash11111856d7865615 > ./patchfile

To create a patch for current git diff:

git diff > ./patchfile

Note: The name patchfile is trivial, you can use any name of your choice.

5. Create a patch of combined commits of a git branch

To create a patch for the whole branch changes compare to the base or any other branch:

git diff base_branch derived_branch > patchfile

6. Apply a git patch

To apply a git patch we’ll use git-apply:

git apply path/to/patchfile

7. Conclusion

When required, patches are lovely! A couple of times I share my changes with friends without sending them a PR on GitHub. You may have your reasons as well 🙂

Thanks for reading!
See you in the next post 🙂

PS: Git is full of surprises!

8. Further read

  1. https://git-scm.com/docs/git-format-patch
  2. https://git-scm.com/docs/git-merge

9. References

  1. https://git-scm.com/
  2. https://stackoverflow.com/questions/42800902/how-to-generate-patch-for-all-commits-in-a-branch

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s