While using git we can create a PR (pull request) to push changes from one git branch into another branch. This is okay if you want to push all changes from one branch into another branch and vice versa
Sometimes however, we do not want to create a full PR to merge two branches of a git repository and just want to change some specific files. This is where git patch comes handy.
In this simple tutorial I will try to show you the commands to create and apply git patch to update selected files of one branch from another branch files.
Create git patch
git diff source_branch destination_branch app/path/to/file_1.ext app/path/to/another/file_2.ext > ~/path/to/patchfile/file_1_file2.patch
As you can see in above example we use the diff
command of GIT. Also, in order to create a git patch you need to know the names of source and destination branches. Also you need to specify the file names which you want to copy changes for with full relative path from the root of your app.
Once you run this command a patch file is created in the patch you specify after >
sign.
Apply git patch
Once the patch file is created, checkout to the branch you want to apply your patch and then run the patch.
git checkout destination_branch git apply ~/path/to/patchfile/file_1_file_2.patch
And your branch should reflect the changes instantly. Now you can create a PR to push these changes to your remote branch or just push the branch to remote origin branch.
I hope that helps someone including myself.