shellstreak

Move a commit from main to a new branch

Careful: rewrites history

Short answer

Run git branch <new-branch>, then git reset --keep HEAD~1, then git switch <new-branch>. The commit now lives only on the new branch.

Only before you push main. --keep refuses to run if it would overwrite uncommitted changes, so nothing unsaved is lost.

The commands, one by one

  1. 1git branch muffins

    Makes a new branch called muffins pointing at your latest commit, so the commit is safe there. You stay on main.

  2. 2git reset --keep HEAD~1

    Moves main back one commit, as if you'd never committed on it. --keep stops if you have uncommitted changes in the way.

  3. 3git switch muffins

    Moves you to the new branch, where your commit is.

For your own repository: Pick your own branch name. If you made several commits on main, use HEAD~2, HEAD~3… to match.

Try it safely

You committed Add muffin recipe on main, but it should have been on its own branch.

learner@shellstreak: ~
Starting your practice shell…

Type your own commands too. Reset puts the repository back to just after the mistake.

Practise this in 5 minutes

Lesson 65, The reflog remembers, walks you through this undo and the ones around it in a safe terminal, step by step, and checks your answers.

Keep the terminal cheat sheet handy: free to print

Get the shellstreak newsletter

Short terminal and Git tips you can try in a minute, plus a heads-up when new free tools and lessons ship. It lands now and then, never a flood.

No spam, unsubscribe in one click.