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:

git@branchMINGW64 /c/example (master)
git checkout -b new-git-branch

git@branchMINGW64 /c/example (new-git-branch)

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:

git@branchMINGW64 /c/example (master)
git swtich -b new-git-branch

git@branchMINGW64 /c/example (new-git-branch)
git add .

git@branchMINGW64 /c/example (new-git-branch)
git commit -m "Add local changes to new git branch"

git@branchMINGW64 /c/example (new-git-branch)
git switch master

git@branchMINGW64 /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.

create branch local changes git

You can do a checkout and create a new branch with all local and current changes transferred over.




App Architecture
Software Quality
Cloud Computing