Git: Diff, Create & Apply Patch

This article shows how you can get differences in the git branch, file, or commits and create and apply git patches.


> git branch 

master
* test

> git checkout test 

> git log --oneline -n 5

04d3d11 (HEAD -> test) Update README
39fdf70 Update hello file
32547fa Add hello file
87ea803 (origin/master, origin/HEAD, master) Update README.md (#904)
00d4c7d Add link

Git diff between two branches


> git diff master..test 

diff --git a/README.md b/README.md
index e2d2954..5a09a7b 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
 # Awesome PHP 

+Hello World!
+
 A curated list of amazingly awesome PHP libraries, resources and shiny things.

 ## Contributing and Collaborating
diff --git a/hello.md b/hello.md
new file mode 100644
index 0000000..e965047
--- /dev/null
+++ b/hello.md
@@ -0,0 +1 @@
+Hello

Git diff of a single file between two branches


> git diff master..test README.md

diff --git a/README.md b/README.md
index e2d2954..5a09a7b 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
 # Awesome PHP 

+Hello World!
+
 A curated list of amazingly awesome PHP libraries, resources and shiny things.

 ## Contributing and Collaborating
 

Git diff between two commits


> git diff commit-hash-1 commit-hash-2

Git diff all files

The following command will show all the modified files and changes that are not added to git or are not staged.


> git diff 

Git diff single or multiple file

The following command will show changes made to a single file that is not added to git or are not staged.


> git diff file-name

> git diff file-name-1 file-name-2

Git diff of a branch

The following command will show all the modified files and changes of a single branch that are not added to git or staged.


> git diff branch-name

Git diff of staged/added files

The following command will show all the modified files and changes that are already added to git or are staged.


> git diff --staged file-name 

Create Git Patch

We can use the above git diff commands and output the result in a patch file. That way we can create the git patch.

The following example creates a patch with the different between two branches (master and test branch) in a patch file named my_custom_changes.patch.


> git diff master..test > my_custom_changes.patch

Apply Git Patch

Apply the newly created patch.

There were changes made to the test branch. So, we will checkout the master branch and apply the patch to the master branch.


> git checkout master 

> git apply my_custom_changes.patch

> git status 

On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    modified:   README.md

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    hello.md

Hope this helps. Thanks.