How to move existing, uncommitted work to a new branch in Git
In software development, it's common to start working on some changes only to realize that these modifications would be better suited in a separate branch. Maybe you're halfway through a feature, bug fix, or some experimental code and want to isolate this work. Thankfully, Git, a powerful version control system, provides an easy way to handle such scenarios. In this Answer, we'll walk you through the steps to move your existing, uncommitted work to a new branch in Git.
The scenario
Imagine you're working on your main branch. After making several changes to a few files, you realize these changes should be on a separate branch.
# Modified filesgit status
Stashing your changes
Before creating a new branch, you might want to ensure a clean working directory. Git offers a handy command called stash that temporarily saves changes that you don't want to commit immediately.
git stash
This command takes your modified tracked files and staged changes and saves them for later use. Your working directory reverts to the state of the last commit.
Creating a new branch
Now, with a clean working directory, create a new branch:
git checkout -b new-feature-branch
This command creates a new branch named new-feature-branch and switches to it.
Applying your stashed changes
With the new branch checked out, you can now apply the changes you stashed earlier:
git stash apply
Your uncommitted changes are now moved to the new-feature-branch.
Committing your changes
Now that your changes are on the appropriate branch, you can commit them:
git add .git commit -m "Start work on a new feature"
What about multiple stashes?
If you've stashed changes multiple times and want to apply a specific stash to your branch, you can list your stashes:
git stash list
This might show something like:
stash@{0}: WIP on main: 049d078 Add the index filestash@{1}: WIP on main: c264051 Revert "Add the index file"
To apply a specific stash, use its name:
git stash apply stash@{1}
Cleaning up
After applying your stashed changes, they remain in your stash. If you no longer need them, it's a good practice to clean up:
git stash drop stash@{1}
Or, if you want to clear all your stash:
git stash clear
Conclusion
Git's flexibility allows developers to manage and organize their codebase efficiently. By understanding commands like stash, you can seamlessly move uncommitted changes between branches, ensuring your work is always in the right place. Whether you're a Git novice or a seasoned professional, mastering these techniques will enhance your version control workflow.
Free Resources