DEV Community

Cover image for Git - Move a commit to another branch
Théo
Théo

Posted on • Edited on

Git - Move a commit to another branch

Use cases

A developer accidentally made changes to an incorrect branch. For example, a commit containing changes related to a new feature is accidentally added to the main branch rather than the specific development branch for that feature

How to do ?

Let's say, you have committed on branch: branchA, instead of commit on branch: branchB.

1 - Go on the branch: branchA

$ git checkout branchA
Enter fullscreen mode Exit fullscreen mode

2 - Show logs

$ git log
Enter fullscreen mode Exit fullscreen mode

And normally the commit should point to the branch: branchA

ex : commit 7988ef64c0d91ed6cf98b2006014b88320a4c8c0 (HEAD -> branchA)
Here, the hash of the commit is : 7988ef64c0d91ed6cf98b2006014b88320a4c8c0

3 - Copy the hash of the commit, and go on the branch: branchB

$ git checkout branchB
Enter fullscreen mode Exit fullscreen mode

4 - Do the cherry-pick command with the hash of the commit (copied previously)

$ git cherry-pick 7988ef64c0d91ed6cf98b2006014b88320a4c8c0
Enter fullscreen mode Exit fullscreen mode

cherry-pick allows copying a specific commit from one branch and applying it to another branch.

5 - Check if the commit has been moved

$ git log
Enter fullscreen mode Exit fullscreen mode

And normally the commit should now point to the branch: branchB
ex : commit 7988ef64c0d91ed6cf98b2006014b88320a4c8c0 (HEAD -> branchB)

Top comments (0)