How to move commits from master to another branch?

You made a series of commits on the master branch, which in hindsight you should have been made in another branch. How to move those commits to another branch?

Setup

The initial state is that you are on the main branch.

alina

983c407mainHEAD

And you push 2 extra commits.

alina

2318ae30330f1f983c407mainHEAD

Then, you realize that the 2 commits, 2318ae and 0330f1, should not be on the main branch but on a separate branch named fix.

Solution description

There are multiple ways to fix this situation, but the simplest solution is described here.

Note: This solution assumes that you have not yet pushed those commits to the origin server. If you have, there would be some extra steps required to properly fix the situation.

You want those 2 extra commits to be on the branch fix, so we start by creating that branch.

alina

alina git:( main ) git branch fix

alina git:( main )

Once done, your commit tree looks like this:

alina

2318ae30330f1f983c407mainfixHEAD

The tree shows:

  • The branch fix is OK: it has the 3 commits you have created so far.
  • The branch main is not OK: it has the last 2 commits that you don’t want there.

To get rid of those 2 commits, use the git reset HEAD{2}--hard command while you are on the main branch.

The syntax HEAD{2} means 2 commits before the current HEAD position.

As HEAD is currently the main branch, that command will drop those 2 commits from the main branch.

alina

alina git:( main ) git reset HEAD@{2} --hard

HEAD is now at 983c407 file created

alina git:( main )

This command allows you to time travel to the state you were in before those 2 commits were created.

alina

2318ae30330f1f983c407fixmainHEAD

All those commits modified a file named file.txt, and you can check its content to confirm that everything is as expected.

alina

alina git:( main ) cat file.txt

Wed May 10 14:28:17 PDT 2023

alina git:( main )

If you switch to the fix branch, you will see the 2 extra changes made by the 2 commits.

alina

alina git:( main ) git switch fix

Switched to branch 'fix'

alina git:( fix ) cat file.txt

Wed May 10 14:28:17 PDT 2023

change1

change2

alina git:( fix )

Problem solved.