Home > Back-end >  How to apply git patch properly after switching branches?
How to apply git patch properly after switching branches?

Time:07-27

I am trying to create a diff & apply a patch. For that I have created a blank text file & committed it, now I am adding "Hello world" in the text file & committing it. Using the git diff command I can see the diff as:

$ git diff
diff --git a/New Text Document.txt b/New Text Document.txt
index e69de29..b0a6290 100644
--- a/New Text Document.txt
    b/New Text Document.txt
@@ -0,0  1 @@
 Helo world
\ No newline at end of file

Now I am creating patch with the command git diff >first.patch. The file gets created, now I am switching to another branch using git checkout -b dummy & here if I try to apply the patch with the below command I get the error as shown. What's wrong?

git apply first.patch
error: patch failed: New Text Document.txt:0
error: New Text Document.txt: patch does not apply

CodePudding user response:

In your example, you created a patch which adds a "Hello world" line to an empty file.

When you run git checkout -b dummy, you create a new branch, but this command does not change the content of files on disk. So New Text Document.txt still has its "Hello world" line, instead of being empty.

Therefore : when you run git apply first.patch, it fails because New Text Document.txt isn't empty.


To test on your current repo : just run git checkout "New Text Document.txt", to reset its content to the starting state expected by your patch.

  •  Tags:  
  • git
  • Related