How to Merge Local Branch with Master without Missing Your Changes?
While you make changes in the local branch, other developers can also merge their changes to the remote master branch. If you push your working branch without pulling remote master branch changes, you will overwrite the other developer’s changes.
This is a very important and common scenario. If there are many developers working on the git projects, you face this issue.
It’s always good practice to update the master branch and merge your working branch with the master before you push your local working branch.
Let’s see how you can do that.
Merge Local Branch with Master without missing Changes
Suppose your local working branch is ‘abc’ and the master branch is ‘master’.
While going through the below steps, refer below git transition diagram. This will make it easy to understand.
Step 1: Stash your local working branch changes
Checkout to your local branch.
git checkout abc
Make new changes to your local branch.
git status command to see all the changes you have made in your local branch.
Now you want to merge your local branch with the master branch without losing any changes.
Stash all the changes in your local branch. (This is important step before you merge. Otherwise, merging local branch with the master will overwrite the local branch changes.)
You have stash all your working branch changes.
Step 2: Update your local master branch with remote
Checkout to the master branch.
git checkout master
You can use the
git branch command to check your current branch.
Ypu can see current branch is changed to your master branch.
Now update your master branch to get all the remote master branch changes.
git pull origin master
origin is nothing but the URL of the remote repo.
After running this command, your local master branch is uptodate.
Step 3: Merge local working branch with master branch
Now again checkout your working branch ‘abc’.
git checkout abc
Again, you can use the
git status command to ensure your current branch is changed to the working branch.
Surprisingly you will not see the changes you made in your working branch. Don’t worry. You will get them back.
Before that merge your working branch with the master branch.
git merge master
Step 4: Get your stash changes and push your working branch
Now, its time to get back all your changes from the stash. You can do that with the simple
git stash pop command
git stash pop
It pops up all the changes you stashed last time.
Do git status.
You will see all the changes you made earlier in the working directory.
You can make any new change you want and then push your branch to remote repo.
git push origin abc
You have done it.
If you are new to the git this looks like cumbersome task. But, you understand it the flow properly and its not difficult.
This is how you can merge local branch with master without missing changes.
If you do it couple of times, you will remember. You can always bookmark this page and use it whenever you stuck.