Say I have uncommitted changes in my working directory. How can I make a patch from those without having to create a commit?
If you haven't yet commited the changes, then:
git diff > mypatch.patch
But sometimes it happens that part of the stuff you're doing are new files that are untracked and won't be in your git diff
output. So, one way to do a patch is to stage everything for a new commit (git add
each file, or just git add .
) but don't do the commit, and then:
git diff --cached > mypatch.patch
Add the 'binary' option if you want to add binary files to the patch (e.g. mp3 files):
git diff --cached --binary > mypatch.patch
You can later apply the patch:
git apply mypatch.patch
We could also specify the files, to include just the files with relative changes, particularly when they span multiple directories e.x.
git diff ~/path1/file1.ext ~/path2/file2.ext...fileN.ext > ~/whatever_path/whatever_name.patch
I found this to be not specified in the answers or comments, which are all relevant and correct, so chose to add it. Explicit is better than implicit!
git diff
for unstaged changes.
git diff --cached
for staged changes.
git diff HEAD
for both staged and unstaged changes.
If you want to do binary, give a --binary
option when you run git diff
.
To create a patch with both modified & new files (staged) you can run:
git diff HEAD > file_name.patch
I like:
git format-patch HEAD~<N>
where <N>
is number of last commits to save as patches.
The details how to use the command are in the DOC
UPD
Here you can find how to apply them then.
UPD For those who did not get the idea of format-patch
Add alias:
git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'
Then at any directory of your project repository run:
git make-patch
This command will create 0001-uncommited.patch
at your current directory. Patch will contain all the changes and untracked files that are visible to next command:
git status .