How to use git patch effectively

Srebalaji Thirumalai
Level Up Coding
Published in
3 min readJul 27, 2020

--

Git provides the option to create patch files. These patch files contain changes that can be used elsewhere.

For example, you can create a patch file in your local repo. Then you can send it to others to use the patch in their local.

Some people will also create a patch to have it as a backup for later use.

Creating git patch

git format-patch <target-branch>

In the above example, you can see that I have mentioned master as the target branch. So Git will fetch all commits from the current branch (develop) which are ahead of master.

Then it creates a patch file for each commit. As you can see there are eight patch files created.

Creating a single patch file for multiple commits

git format-patch <target-branch> --stdout patch_name.patch

In the above example, a single patch file is created with a given name for all the commits.

Creating a patch from git commits

Sometimes, you are interested in creating a patch from a selective commit. In this case, you can use

git format-patch -1 <commit-hash>

The above command will only consider the respective commit hash to make a patch.

Applying git patch

Now you know how to create a patch file. Let’s see how to apply the git patch if you got one.

You can see that I have applied a patch file from the destined path. Then the changes are applied from the patch file. Then you can review those changes and do the commit.

git apply --stat <patch_file_path>

This command will not apply the patch but will show the changes stat.

Using git am

This command will apply the patch and a new commit is created from the changes. Unlike apply it won’t be just used to preview the changes. git am will create new commits.

Patches are helpful if you want to share code with others without using your centralized repo. And it is also useful to take a backup of your work for later purposes.

Thank you for reading, I hope you learned something new :)

You can find my other git related articles here

1. How to use git stash effectively2. How to use git blame effectively3. How to squash git commits4. How to rewrite the latest commit with git amend5. Useful tricks you might not know about git log6. How git revert works7. How git cherry-pick works and how to use it effectively8. Automate repetitive tasks in Git9. Useful tricks of git fetch and git pull10. A very basic intro of Git

If you have come this much, then I think you are much interested in Git. You can subscribe to my newsletter GitBetter to get tricks, tips, and advanced topics of Git.

--

--