Create Git patches from command line
Git patches are an easy way to apply changes to a project if you don’t want to go through the regular commit-pull-request flow. Patches are files that contain an equivalent diff of a Git commit.
You can create a patch of your modified working state using
git diff. The
diff output is in the correct patch format.
$> git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: hello.txt no changes added to commit (use "git add" and/or "git commit -a") $> git diff > ~/important-changes.patch
This will create a simple patch file that can be applied to a different repo and will create the same file changes in the working directory:
$> git status On branch master nothing to commit, working tree clean $> git apply ~/important-changes.patch $> git status On branch master Changes not staged for commit: [...] modified: hello.txt
What’s also possible is to create a formatted patch from commits which includes the commit metadata. These patches were created to be sent via email.
You can use
git format-patch <since> to create a patch from all commits since a certain point, or within a range, respectively.
$> git format-patch origin/master --output ~/ /home/sebastian/0001-changed-file.patch /home/sebastian/0002-changed-file-again.patch # or into a single file $> git format-patch origin/master --stdout > ~/important-commits.patch
Again, these changes can be applied using
git apply. Now, we can also use
git am to apply all commits including their metadata:
$> git am ~/important-commits.patch Applying: changed file Applying: changed file again
These patches can be helpful for local workaround that you need to apply to codebases every now and then.
The content of this post was reposted from my newsletter issue 037.
Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Create Git patches from command line
Opinions expressed by Java Code Geeks contributors are their own.