Git is a gift that keeps giving
Stuck in a weird situation where you have some local changes but you are not in a position to commit and push / stash / put it off in a different branch? just want an extra copy for safe keeping all the changes you had done? Well git patch is one way you can deal with it.
Here are the primary Git commands you would use to create and apply patches of your uncommitted changes:
1. Creating a Patch from Uncommitted Changes:
To create a patch file containing your current unstaged and staged changes, you use the git diff
command and redirect its output to a file.
For all uncommitted changes (staged and unstaged):
git diff HEAD > my_changes.patch
This command compares your current working directory and staging area against the HEAD
commit (the latest commit on your current branch) and outputs the difference in the unified diff format. The >
redirects this output to a file named my_changes.patch
.
For only staged changes:
git diff --cached > staged_changes.patch
Or
git diff --staged > staged_changes.patch
This command compares your staging area against the HEAD
commit.
For only unstaged changes:
git diff > unstaged_changes.patch
When git diff
is used without additional arguments (like HEAD
or --cached
), it compares your working directory against the staging area.
2. Applying a Patch:
To apply a patch file that you have created or received, you use the git apply
command:
git apply path/to/your/patch_file.patch
Replace path/to/your/patch_file.patch
with the actual path to the patch file.
Useful git apply
options:
--check
: This option will test if the patch can be applied cleanly without actually applying it. This is a good idea to run before applying a patch.
git apply --check path/to/your/patch_file.patch
--stat
: This option shows a summary of the files that will be changed by the patch without applying it.
git apply --stat path/to/your/patch_file.patch
The "Copy Changes (Patch)" functionality within VS Code's Source Control panel just copies the changes to your clipboard.
Here's an example of how the content would look like in the patch file when you add my_changes.patch
to the .gitignore
file.
diff --git a/.gitignore b/.gitignore
index be34202..587e8e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,3 +20,4 @@ yarn.lock
/playwright-report/
/blob-report/
/playwright/.cache/
+my_changes.patch
\ No newline at end of file
Credits:
- Problem faced by me, the solution provided by gemini 2.5 flash preview model.
- Cover image generated using https://coverview.vercel.app/editor
Join Shreyas on Peerlist!
Join amazing folks like Shreyas and thousands of other people in tech.
Create ProfileJoin with Shreyas’s personal invite link.
0
11
0