0

I made some changes locally in my main branch and committed, but not pushed. Now, I changed my mind and I would like to create a new test branch, take all the changes that would be pushed, commit them to the new branch and remove from the main branch.

So (not a real output, wrote it by hand):

# get the code git clone ... # I am in the main branch git branch * main # ...do some changes... # and commit them git commit --all # I am ahead by 1 commit git status Your branch is ahead of 'origin/main' by 1 commit # I changed my mind, I don't want to # git push # I want to move those changes to a new branch git checkout -b test # WHAT NOW? # - move the changes that are "ahead" to the "test" branch # - restore the main branch to the state before the commits 

1 Answer 1

5

The changes "ahead" are simply those between origin/main and main. So, to reset main to its old state, you need to just git reset --hard origin/main. The full setup from WHAT NOW would be:

git checkout main git reset --hard origin/main 

...and that's it. Note that the first step of "WHAT NOW" is already done by git checkout -b test, so the only remaining step is restoring main to origin/main.

NOTE: this assumes that the changes have been committed, as stated in the question. Running git reset --hard on a checkout with uncommitted changes will make you lose your changes. If you are not sure whether the changes have been committed, run git status; after a successful commit, it will tell you that there is nothing to commit.

Sign up to request clarification or add additional context in comments.

5 Comments

I thing i missed something... I did the reset --hard and it wiped out all the files that I worked on and did not commit them!
@JakubM. Don't forget that you're on the main branch, now restored to the state before the commits, as you requested. To get back to your files, issue git checkout test.
I didn't commit to test branch. Fortunately I had backup. Remember kids, commit your changed and do backups.
@JakubM. Ouch - glad you recovered your files!
@JakubM. Well, my answer is written under the premise that the files have been diligently committed, as stated in the question! And besides being explicitly stated in the question, committing often is always recommended when using git.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.