Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating patch files in git

Tags:

git

I wanted to know whether it is possible to create patch files in git. I mean if I have done some changes in few files then patch file should be created with respect to the filename.

git diff displays the changes on the console but Is it possible to separate the output into different files?

like image 967
BeginnersSake Avatar asked May 19 '26 00:05

BeginnersSake


2 Answers

git format-patch

Say you've made a commit aaa111 which modifies foo.txt, bar.txt and hello.txt.

git format-patch -1 aaa111

It generates a patch including three files' changes.

git format-patch -1 aaa111 -- foo.txt

It generates a patch including only the change of foo.txt.

git format-patch -1 aaa111 --stdout -- bar.txt > aaa111.bar.patch

It generates a patch named as aaa111.bar.patch which includes only the change of bar.txt

Update 2022-06-04

For the commit that touches binaries, you should add --binary to git format-patch.

like image 110
ElpieKay Avatar answered May 21 '26 14:05

ElpieKay


The following script creates patches for the files modified on the most recent commit (HEAD~1):

# Enumerate the files modified on the desired commit
for file in $(git diff --name-only HEAD~1); do
    # Generate the name of the patch file: replac '/' with '_'
    # in the paths of the modified files and add the .patch termination
    patch=${file//\//_}.patch
    # Create one patch for each modified file
    git diff HEAD~1 -- $file > $patch
done

You can modify the generation of the patch file name to include a path (to not generate them in the current directory). Also to generate a diff between different commits, replace HEAD~1 in both places with the appropriate commit(s) identifiers.

like image 33
axiac Avatar answered May 21 '26 13:05

axiac