How to move the last commit to a different branch?

git checkout right_branch
git cherry-pick SHA

To move the last commit to a different branch, you will first need to find the commit SHA with git log.

Once you have the SHA of the commit, checkout the right branch with git checkout and cherry pick your selected commit with git cherry-pick. This will add your commit to the right branch

If you want to remove the last commit from the wrong branch, checkout the wrong branch and run git reset on it.

Layer 1
Terminal Example
git log --oneline
f3d6379 (HEAD -> wrong-branch) Commit which needs to move
c335861 (main, right-branch) Changes in code and README
b2626e9 Adding file with branch name

git checkout right-branch
Switched to branch 'right-branch'

git cherry-pick f3d6379
[right-branch d2b24a7] Commit which needs to move
 Date: Wed May 26 14:44:58 2021 +0200
 1 file changed, 1 insertion(+)

git checkout wrong-branch
Switched to branch 'wrong-branch'

git reset --hard HEAD~1
HEAD is now at c335861 Changes in code and README


See git checkout and git cherry-pick to learn more about them.

Last modified on November 30, 2021.

You might also like