Safety Moving Uncommitted Changes to A New Branch in Git

Sometimes while working on the master branch, you might find that your changes would be better suited on a different branch. Whether it’s because the scope of the work expanded or simply due to a change in plans, moving uncommitted changes to a new branch and resetting the current one can help keep your project history clean and organized. Here is a step-by-step guide on how to do just that.

What to do

  1. Stash Your Uncommitted Changes
  2. Create and Checkout the New Branch
  3. Revert the Master Branch to the Last Commit
  4. Apply the Stashed Changes to the New Branch

Step 1: Stash Your Uncommitted Changes

Firstly, ensure you’re on the branch that currently has the uncommitted changes. If not, switch to it. In this case, it’s the master branch.

git checkout master

Now, let’s safely store the uncommitted changes away temporarily using git stash.

git stash

This command will take all your modified tracked files and staged changes and store them in a stack of unfinished changes that you can reapply at anytime.

Step 2: Create and Checkout the New Branch

The next step is to create a new branch where you want these changes to be moved. Let’s name this branch dev_branch.

git checkout -b dev_branch

With the -b flag, Git will create a new branch named dev_branch and immediately switch to it.

Step 3: Revert the Master Branch to the Last Commit

After creating and switching to the new branch, we need to ensure our master branch is reset back to its last commit state.

First, go back to the master branch:

git checkout master

Then, revert the master branch to the last committed state with:

git reset --hard HEAD

This command resets the master branch to its latest committed state, discarding any uncommitted changes.

Step 4: Apply the Stashed Changes to the New Branch

Now that master is clean and stable, it’s time to bring your changes over to dev_branch.

Switch back to dev_branch:

git checkout dev_branch

And finally, apply the stashed changes:

git stash apply

Your uncommitted changes from the master branch are now present in dev_branch, and you’re ready to continue your work there.

Note: This process ensures that your master branch remains clean and free from potentially unstable changes, while allowing you to continue development in an isolated environment appropriate for your new features or bug fixes.

Remember, stashes are local to your Git repository, so if you’re working in a shared environment, rest assured that your stash won’t be seen by others unless you push it to a remote repository.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.