Suppose we have created two branches, namely master and work, we developed a few features and fixed a few bugs on the work branch, and we want to merge the bug fixes to the master branch. Below are the steps that should be carried out.
0. Check out the commits range
Make sure we’re at work branch. We can use either “git log” or a GUI tool like gitk to see what are the start and end commit SHA1 IDs. Below is a sample output of “git log”.
Suppose we want to merge the first two commits from the work branch to master branch. The SHA1 ID are 315125… and 46e768… respectively.
1. Check out a temporary branch
This can be done with the command below,
git checkout master
git checkout -b tmp
This branch tmp will be the same as master branch. And now we’re at tmp branch.
2. Move work branch ahead
This can be done with the following command,
git branch -f master 315125
We only need to provide the first few digits of the SHA1 ID, git is smart enough to figure it out the rest. This will set the master branch to contain all the commits up to commit 315125.
This is done with command below,
git rebase –onto tmp 46e768~1 master
46e768 is the start commit number we want to merge to master branch. This will rebase master branch to tmp branch + all commits between 46e768 and 315125. Since tmp branch contains the what the original master branch contains. This is equivalent to adding commits from 46e768 to 315125 to master branch.
In case there’s any conflicts, we’ll need to resolve the conflict and run
git rebase –continue
After it’s done, we’ll be at master branch, ready to push the changes.