How to Move a Commit to Another Branch in Git

Moving a commit to another branch in Git is pretty straightforward. You’ll usually want to do it to tidy up your project’s history, for e.g. if you accidentally committed to the wrong branch. This post covers the techniques you’d use to move Git commits so read on if you want to keep your projects more organized.

How to create and switch to the new branch?

If the target branch doesn’t exist, you first need to create it from the current state of the main branch. If the branch already exists and you simply want to add the commit to it, proceed to checking out the target branch.

git branch feature-x

How to check out a target branch in Git?

Switch to your intended branch, feature-x, with the following command:

git checkout feature-x

How to cherry-pick a commit in Git?

Find the commit you wish to move by using git log to get its hash. With the commit hash in hand, let's say abc1234, cherry-pick it onto your current branch (feature-x) using:

git cherry-pick abc1234

How to move back to the original branch in Git?

Return to the main branch by running:

git checkout main

How to revert a commit on the original branch in Git?

You’ll want to be sure that removing this commit from the main branch doesn't disrupt your branch's history. If you've pushed the commit, consider using git revert to avoid issues with shared history.

To remove the commit locally without pushing, you can:

git reset --hard HEAD~1

This command discards the last commit on main, so use it with caution to avoid losing work.

For commits that have been shared or if you need to maintain a clean history for collaborators, revert the commit using:

git revert abc1234

This action creates a new commit on main that undoes the changes made by abc1234.

Push changes if necessary

If your commits have been shared remotely, and you've used git revert, then push your updates:

git push origin main git push origin feature-x

In cases where you've used git reset and are sure it won't affect others, you might consider a force push, though this is generally advised against:

git push origin main --force

Invite only

We're building the next generation of data visualization.