When working with Git, you might find yourself making changes on the wrong branch or decide that your modifications should be on a new branch to keep the main branch clean or for other reasons. Fortunately, Git offers flexibility to move uncommitted changes to a new branch. Here are the steps:
-
Check current changes: Before moving the changes, check the status of your working directory and staging area. You can use the following command:
shellgit statusThis will display the status of your current changes, whether they are staged or unstaged.
-
Create and switch to a new branch: If you have staged the changes, unstage them first (if you intend to move them to the new branch). Then, create and switch to a new branch using the following command:
shellgit checkout -b new-branch-nameThis command creates a new branch named
new-branch-nameand switches to it. -
Add and commit changes: Now that you are on the new branch, add and commit your changes. Use the following command to stage all changes:
shellgit add .Or, if you want to add specific files, use:
shellgit add <file-path>Next, commit the changes to your new branch:
shellgit commit -m "Commit message explaining the changes" -
(Optional) Keep the main branch clean: If you just created the new branch from the main branch (e.g.,
mainormaster) and don't want these changes to appear on the main branch, switch back to the main branch and discard these changes. First, switch back to the main branch:shellgit checkout mainThen, use the following command to discard uncommitted changes:
shellgit reset --hardThis will reset the main branch to the last commit state, discarding all uncommitted changes. Note that this is a dangerous operation as it discards all uncommitted changes. Before using
git reset --hard, ensure you don't need these uncommitted changes.
This is the basic process for moving uncommitted work to a new branch. Let's look at a specific example:
Suppose you are working on the main branch main and have made some changes. Now you want to move these changes to a new branch feature-x.
- Check changes:
sh
git status - Create and switch to new branch
feature-x:shgit checkout -b feature-x - Stage all changes and commit them to the new branch:
sh
git add . git commit -m "Start working on feature X" - If needed, switch back to
mainbranch and discard changes:shgit checkout main git reset --hard
Now, the new branch feature-x contains the previously uncommitted work, while the main branch remains unchanged.