When working with Git, there might be times when you need to move commits from one branch to another. This guide will walk you through the process of moving commits using different methods such as git cherry-pick
.
Moving the last commit to another branch
Step 1: Create and switch to the target branch
First, create the new branch (if it doesn't already exist) and switch to it:
git checkout -b <new-branch>
Replace <new-branch>
with the name of the branch you want to create and move your commit to.
Step 2: Cherry-pick the last commit
Next, you can use git cherry-pick
to apply the commit from the source branch to the target branch. If you're moving the last commit, you can run:
git cherry-pick <commit-hash>
To get the commit hash of the last commit, run:
git log -1
Copy the hash and use it in the cherry-pick command.
Step 3: Remove the commit from the original branch
Switch back to the original branch:
git checkout <source-branch>
Then, reset the branch to remove the last commit:
git reset --hard HEAD~1
This command will reset the branch to the state before the last commit, effectively removing it.
Moving multiple commits to another branch
Step 1: Identify the commits to move
Use git log
to identify the commit hashes you want to move:
git log
Step 2: Create and switch to the target branch
Create the new branch and switch to it:
git checkout -b <new-branch>
Step 3: Cherry-pick the commits
Cherry-pick the commits one by one or use a range:
git cherry-pick <commit-hash1> <commit-hash2> ...
Or for a range of commits:
git cherry-pick <commit-hash1>^..<commit-hashN>
Step 4: Remove the commits from the original branch
Switch back to the original branch:
git checkout <source-branch>
Then, use interactive rebase to remove the specific commits:
git rebase -i <commit-hash>^
In the interactive rebase screen, change the command for the commits you want to drop from pick
to drop
.
Using rebase to move commits
Another method to move commits is by using git rebase
. This can be useful if you want to move a series of commits from one branch to another in a more automated fashion.
Step 1: Create and switch to the target branch
Create the new branch and switch to it:
git checkout -b <new-branch>
Step 2: Rebase onto the new branch
Switch back to the source branch and rebase it onto the new branch:
git checkout <source-branch>git rebase <new-branch>
Step 3: Force push the changes (if necessary)
If you are working on a remote repository and need to update the branches, you may need to force push the changes:
git push --force
Be cautious with force pushing as it can overwrite history.
For more information see this guide on cherry-picking in Git.