Open In App

Patch Operation in Git

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Git patch is a feature in git which enables you to create a patch file from a feature in one branch and apply it in another branch.
A patch file has all the differences between the two branches. Using the patch file, we can apply the changes in a different branch.
This can be visualized as – Suppose you are working on a project. The main project is in the “master” branch. You are working on a feature on a separate branch named “feature1”. Now, you make all the changes in the “features1” branch and then create something known as a “patch file”. Now, this patch file can be used in the master branch to add that particular feature you worked on.

Creation and Working of Patches

Let’s see the following example:

Step 1: There is a repository named ‘Pat’. The user created a file “text.txt” in the master.

 
Step 2: Then it is added to the master branch and the change is committed with a message “initial”.

 
Step 3: Checking logs

 
Step 4: Now, let create a new branch named feature and checkout to our feature branch.

 
Step 5: Change the “text.txt” by adding a few words.

 
Step 6: Next, we will save these changes, add and commit the changes in our feature branch with a message “this is in feature branch”.

 
Step 7: Checking logs

 
Step 8: Now comes the main part- Creating a patch file. For creating a patch file we will write

git format-patch {branch in which we will apply our patch file} -o {folder in which we will save our patch file}

Currently, we are in the feature branch. We need to compare our changes to the branch where we want to apply our changes(here master branch). Then we use “-o” and specify the folder in which the patch file will be created (this is optional).

We can also create a patch file using a particular commit’s hash key. For example:-

git format-patch -1 012fe999affd9b92f6c96eb72a7260273411ea81 -o patches

The hash key is present in the git log written in dark yellow.
 
Step 9: Now, we come back to our master branch and check our “text.txt”.

Note: Here, “cat text.txt” is used to view the file. This may not run in Windows. Please use Notepad or any code editor to view this.

 
Step 10: Now, we finally apply our patch file in the master branch.

git am {path to patch file}


 
Step 11: Checking logs


Last Updated : 22 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads