Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GIt - how to create and switch to a branch when I already modify the code?

I wrote some code while in master, and realize that I am doing some experiment that I don't want to put in the master yet. Reading this documentation, it seems that I should have done

git checkout -b experiment

Before I even started writing the code. How should I proceed now? I'm afraid if I execute the command above, what happens will be

  1. A branch experiment will be created (duplicated from master)
  2. Git will checkout from this new branch, which means I will lose my work.

How can I commit my current work to a new branch without affecting master?

like image 518
Louis Rhys Avatar asked Jan 25 '26 18:01

Louis Rhys


1 Answers

Carl has the correct answer, but I just wanted to add that if the work you did wasn't committed yet, another option would have been to just stash your changes to save your work before you switched to the new branch:

$ git stash save
$ git checkout -b new-branch
$ git stash pop

The first command saves your changes to the stash, and makes your working directory clean. Then you make your branch, and then you remove your changes from the stash and apply them to the branch. Done!


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!