A classic mistake faced by every git user

02 / Feb / 2022 by Harsh Vardhan Gupta 0 comments

Learning from mistakes will teach us a lifelong lesson, similarly here we are discussing a classic mistake that every git user made at least once i.e. committing code in the wrong branch. 

If you identify the mistake at the right time this can be easily managed, but it gets more tricky if you start committing code in the wrong branch. Let’s take a problem statement to understand the issue more clearly.

Problem Statement

You are working on a new feature and you forgot to change a new branch for it. You’ve already done lots of work and committed in the master branch, now you’ve realized you need to switch to a new feature branch keeping all work secure that you already committed in the master branch.

Solution

git stash is the solution provided by git to prevent us from this mess. Follow the commands below to switch to the correct branch without losing your committed code.

$ git checkout new-feature

If this succeeds, no need to worry, just commit your changes and push the changes in the new branch. In case the above command raises an error like the one below

error: Your local changes to the following files would be overwritten....

Then execute the command below

$ git stash

This command safely stores your changes in a local repository, and now you can switch your branch without worries.

$ git checkout new-feature
$ git stash apply

Now you can see all your changes in the new feature branch. If everything goes well make sure to execute $ git stash drop, and it’ll drop the reference of the branch created in your local repository.

FOUND THIS USEFUL? SHARE IT

Tag -

git

Leave a Reply

Your email address will not be published. Required fields are marked *