Search code examples
gitbranchcommitgit-amend

Can I use the 'Amend last commit' in Git to transfer the changes to another branch?


I accidentally made a commit in the wrong branch but since I can do Amend I'm thinking if it's possible to use it to transfer the changes to the right branch. Can I change branch instead and do the amend there or will it be applied to the same branch where it was committed?


Solution

  • Assuming you have not yet pushed the first branch with the mistaken commit, you may try cherry picking it to the right branch, then rolling back the first branch:

    # switch to correct branch, and cherry-pick desired commit
    git checkout branch2
    git cherry-pick <SHA-1 of commit>
    
    # then switch to first branch, and remove incorrect commit
    git checkout branch1
    git reset --hard HEAD~1
    

    The <SHA-1> of the commit you want can be found by using git log branch1. Note that if you have already pushed branch1, then a safer option would be to git revert that commit. But, you may still use cherry picking to move the commit to the second branch.