CLI
I accidentally worked on the wrong Git branch. What should I do now?
Published by Sven Kalbhenn · 0 Comments
What to do if you accidentally worked on the wrong Git branch.
You’ve already made a few changes to your Git repository and suddenly realize that you’ve been working on the wrong branch the whole time (e.g., “main” instead of “develop”)?
Sound familiar? It’s happened to me plenty of times.
What now? What’s the easiest way to get the changes into the right branch?
Here are the answers—the options available to you in this situation:
1. Haven’t committed yet?
The easiest way is if you haven’t “committed” the changes to the repository yet:
Save all changes to a “stash.” Switch to the correct branch and then restore the changes from the stash.
git stash
git checkout <correct_branch>
git stash pop
2. Merge all changes?
If you’ve already made several commits to the “wrong” branch, the question is whether you want to merge all commits into the “correct” branch, or just specific ones?
If you want to incorporate all commits, you can simply “merge” the two branches together:
git checkout <correct_branch>
git merge <wrong_branch>
3. Incorporate only specific changes (cherry-pick)?
If you’ve already made several commits to the “wrong” branch and now want to incorporate only specific commits into the “correct” branch, “cherry-picking” is the way to go:
First, view the Git log and note down the hashes of the commits you want to incorporate. Then switch to the “correct” branch and use `git cherry-pick` to incorporate the commits you identified earlier.
git log
/* note the hashes of the commits */
git checkout <correct_branch>
git cherry-pick <hash>
Do you have any other ideas on how to solve this problem? Then let me know (sven@skom.de)!
About the Author: Sven Kalbhenn
Senior TYPO3 Consultant & Software Developer
Write comment
Your email is never published.
Comments (0)
No Comments