shellstreak

Move a commit to another existing branch

Careful: rewrites history

Short answer

Switch to the right branch and git cherry-pick the commit, then switch back and git reset --keep HEAD~1 to remove it from the wrong branch.

Removing the commit from the wrong branch rewrites it: only do that part if you haven't pushed that branch.

The commands, one by one

  1. 1git switch fixes

    Go to the branch the commit belongs on.

  2. 2git cherry-pick main

    Copies the latest commit of main onto fixes as a new commit with the same changes and message.

  3. 3git switch main

    Back to the branch that got the commit by mistake.

  4. 4git reset --keep HEAD~1

    Takes main back one commit. The copy on fixes stays.

For your own repository: Instead of main, you can give the commit's hash from git log --oneline.

Try it safely

You committed Fix salt amount on main, but fixes go on the fixes 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 64, Copy one commit: cherry-pick, 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.