DEV Community

Manish Rana
Manish Rana

Posted on

Apply changes from one branch to a newer branch created from MAIN or MASTER branch using GIT STASH

CASE: We sometimes tend to forget to checkout to a newer clean branch created from the master branch (yes, I did that) and make changes in the same branch which we currently are. Then we suddenly realize the new changes must be in the newer branch (yes, I did realize that when I made that mistake). For that, we have GIT STASH to the rescue.

As we can see in this case we might not know that when we use GIT STASH the changes can be applied to any branch we have created in the project.

I normally would tend to GIT STASH the changes in the current branch that I was working on so I could go to another branch with bugs to be fixed. Then I would come back to the current working branch and GIT STASH APPLY to apply the changes that were stashed.

But as for the CASE explained above we can also apply the changes to the newer branch created from another branch. Generally, we create a new fresh branch from a branch that is deployed to the server and stable.

Suppose we are in a branch feature/payment and we need to make changes in the newer branch feature/billing which we might be required to create from master or main or any other stable branch.

Note: When using GIT STASH remember that the changes from the last commit are stashed. So, if the changes required for feature/payment are already committed, only the newer changes will be stashed. Otherwise, the changes made for the feature/payment will also be stashed. Then, when you do GIT STASH APPLY, all the changes will be applied until the last commit (which we don't want).
Please learn about GIT STASH for more.

For that we can do as follows:

git stash 
//changes on the feature/payment branch i.e. current branch are stashed

git checkout main      
//checking out to the main or master or any other stable branch

git checkout -b feature/billing  
//creating a newer branch from the 'main'  branch and checking out to that branch

git stash apply
//apply the latest stash to the current branch i.e.
feature/billing which has changes stashed from feature/payment
the branch which should be in the feature/billing branch

Enter fullscreen mode Exit fullscreen mode

Top comments (0)