How to Use Patch Files in Git

John Wachira Feb 02, 2024
How to Use Patch Files in Git

In this tutorial, we will introduce Git patch files. The article covers the following topics.

  1. How to create Git patch files for commits?
  2. How to view altered files in a patch?
  3. How to check for errors?
  4. How to apply a Git patch?

We use a Git patch file to store the changes from commits. A patch file will include data like the date of a commit and message.

You can use a Git patch to apply changes to your repository. These patch files come in handy when you do not have writing access.

Create a Patch File From Commits in Git

We use the git format-patch command to generate patch files.

To create a patch file for a specific number of commits before the selected commit, apply the -N option to your command.

git format-patch -N <sha1-commit-hash>

An alternative to the commit hash is HEAD.

git format-patch -N HEAD

To create a patch file for a specific range of commits, use the command below.

git format-patch <first-commit-hash>^..<end-commit-hash>

Add stdout>file.patch to your command to create one file for several commits.

To view all changes in your patch file, run the git apply --stat <file.patch> command.

git apply --stat <file.patch>

The command above specifies the patch file to read from.

If you want to apply the patch to your repository, use the command below.

git apply <file.patch>

The git format-patch command will store your commit in a UNIX mailbox format. You can send and receive patch files via email.

When running the git apply command to apply a patch, Git will ignore the patched paths not present in your repository’s working directory.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Patch