How to create git patch


In Git, a patch is a file that contains the changes made to a file or set of files. It can be used to apply changes from one branch to another or to share changes with others who do not have access to the original Git repository. Here’s how to create a patch file in Git:

  • Make the changes you want to include in the patch file.
  • Stage the changes using the git add command.Replace <file1>, <file2>, etc. with the names of the files you want to include in the patch.
git add <file1> <file2> ...
  • Commit the changes using the git commit command
git commit -m "Commit message"
  • Generate the patch file using the git format-patch command.The -1 option specifies that you want to create a patch file for a single commit. The HEAD argument specifies that you want to create a patch file for the most recent commit.
git format-patch -1 HEAD
  • The patch file will be created in the current directory with a name like 0001-Commit-message.patch.

Example:

Suppose you made changes to a file named example.py and want to create a patch file for those changes. Here are the steps you would follow:

  1. Make the changes to example.py.
  2. Stage the changes using the command git add example.py.
  3. Commit the changes using the command git commit -m "Added new feature to example.py".
  4. Generate the patch file using the command git format-patch -1 HEAD.
  5. A patch file named 0001-Added-new-feature-to-example.py.patch will be created in the current directory.

You can now share the patch file with others or apply it to another branch using the git apply command.