using patch command with git, and how to reverse it
The patch command is an old tool that is still useful when changes need to
move between machines without push or remote access. A typical case is an old
server without git access, or a small fix that is easier to send by email as
a text file.
Creating a patch
If the changes are already inside a git repository, git can create the patch file for you:
$ git diff > fix.patch
The uncommitted changes become one file. To export a specific commit, use
git diff HEAD~1 > fix.patch or git show <commit> > fix.patch.
Applying a patch
Copy the file to the target machine, then run:
$ patch -p1 < fix.patch
teh -p1 option deserves attention. Git writes file paths like
a/src/app.py, where a/ and b/ are prefixes added by git. -p1 tells
patch to strip one level of that prefix so it finds the correct file. If
patch reports that it cannot find the file to patch, this is usually the
reason.
It is good practice to test with a dry run first:
$ patch --dry-run -p1 < fix.patch
If the target is also a git repository, git can apply the patch directly:
$ git apply fix.patch
git apply understands the git format better, and the result can be managed
with normal git commands afterwards.
Reversing a patch
An applied patch can also be undone. The -R option applies the patch in
reverse:
$ patch -R -p1 < fix.patch
With git the idea is the same:
$ git apply -R fix.patch
The patch file is plain text and works in both directions, so the original file is enough. There is no need to create a seperate undo patch.
Notes
- If patch complains about whitespace,
git apply --whitespace=fixcan help. - Binary files (images, pdf) are not handled well by
patch. Usegit format-patchandgit applyinstead, they support binary content. - When a hunk fails to apply, patch leaves
.origand.rejfiles behind. The.rejfile contains the rejected part and is worth reading before trying again. - A dry run before applying on production is not optional. I learned that after one messy apply on a production config.
- Keep the
.patchfile until the change is confirmed good, the same file serves as the undo button.
The patch command is simple and old, but it has saved me many times when
the proper solution, git remote or ansible, would be overkill for one small
fix.
- [ ] Ref: https://man7.org/linux/man-pages/man1/patch.1.html
- [ ] Ref: https://git-scm.com/docs/git-apply