Create a new Git branch with current local changes saved by example
Did you do some development on the main or master branch without switching to a new, isolated feature branch?
Git branch create with local changes example
Don’t worry, you can easily create a new Git branch without losing your local changes. Just use Git’s switch or checkout commands, and your new branch will be created with all of your current changes left intact. Just run the following command:
[email protected] /c/example (master) git checkout -b new-git-branch [email protected] /c/example (new-git-branch) ls
The new Git branch will be created the local changes you made on the other branch waiting there for you. Nothing has been deleted.
Save current changes in a new Git branch
It is worth mentioning that all of those local files you added to the original branch are still there. So if you created a bunch of files in the master branch before you created the new Git branch with your current changes, the master branch is still polluted with the files you added to the index before the switch to the new branch happened. If you want to clear your changes from the master branch, you can perform a git clean after the new branch is created.
The sequence to create a new Git branch with local changes in tact, but remove those changes from the original branch, the sequence of commands would look like this:
[email protected] /c/example (master) git swtich -b new-git-branch [email protected] /c/example (new-git-branch) git add . [email protected] /c/example (new-git-branch) git commit -m "Add local changes to new git branch" [email protected] /c/example (new-git-branch) git switch master [email protected] /c/example (master) git clean -f
Note that in the above example, we used Git switch, not checkout. The Git switch command came out in 2020, and is preferred over the git checkout command.
When this sequence of Git commands is completed, the new Git branch will have all your current changes stored locally, while the original branch where you inadvertently wrote some code will have its working tree reset to the state at the point of its last commit.