How to Move a Commit to Another Branch in Git
To move a commit to another branch in Git, first switch to the target branch using
git checkout or git switch, then apply the commit with git cherry-pick <commit-hash>. After that, remove the commit from the original branch using git reset --hard HEAD~1 if it is the latest commit.Syntax
Here are the main commands to move a commit from one branch to another:
git checkout <target-branch>orgit switch <target-branch>: Switch to the branch where you want the commit.git cherry-pick <commit-hash>: Apply the commit from the original branch onto the current branch.git checkout <original-branch>: Switch back to the original branch.git reset --hard HEAD~1: Remove the last commit from the original branch (use carefully).
bash
git checkout <target-branch>
git cherry-pick <commit-hash>
git checkout <original-branch>
git reset --hard HEAD~1Example
This example moves the latest commit from branch feature to branch main.
bash
git checkout main # Apply the commit from feature branch # First, find the commit hash on feature branch commit_hash=$(git log feature -1 --format=%H) git cherry-pick $commit_hash # Switch back to feature branch git checkout feature # Remove the last commit from feature branch git reset --hard HEAD~1
Output
Switched to branch 'main'
[main 1a2b3c4] Commit message from feature branch
Switched to branch 'feature'
HEAD is now at abcdef0 Previous commit message
Common Pitfalls
- Not switching branches: Trying to cherry-pick without being on the target branch will apply the commit to the wrong place.
- Resetting incorrectly: Using
git reset --harddeletes commits permanently if not careful. Always double-check the commit history before resetting. - Multiple commits: If moving multiple commits, cherry-pick each or use a range carefully.
- Uncommitted changes: Make sure your working directory is clean before cherry-picking or resetting to avoid conflicts.
bash
## Wrong way: cherry-pick on original branch # git cherry-pick <commit-hash> ## Right way: git checkout <target-branch> git cherry-pick <commit-hash>
Quick Reference
| Command | Purpose |
|---|---|
| git checkout | Switch to the specified branch |
| git switch | Alternative to checkout for switching branches |
| git cherry-pick | Apply a commit from another branch |
| git reset --hard HEAD~1 | Remove the latest commit from current branch |
| git log | Get the latest commit hash from a branch |
Key Takeaways
Always switch to the target branch before applying the commit with cherry-pick.
Use git reset --hard carefully to remove commits from the original branch.
Check your commit hash with git log before cherry-picking.
Keep your working directory clean to avoid conflicts during cherry-pick and reset.
For multiple commits, cherry-pick them one by one or use a commit range.