This often happens to me: I write some code, go to check in my changes, and then realize I'm not in the proper branch to check in those changes. However I can't switch to another branch without my changes reverting. Is there a way to move changes to another branch to be checked in there?
To move these changes to an exiting branch, just checkout the other branch with the regular checkout command. For example, run this command where “existingbranch” is the name of an existing branch.
git stash
is your friend.
If you have not made the commit yet, just run git stash
. This will save away all of your changes.
Switch to the branch you want the changes on and run git stash pop
.
There are lots of uses for git stash. This is certainly one of the more useful reasons.
An example:
# work on some code git stash git checkout correct-branch git stash pop
Update: No need to use stash
command. uncommitted changes do not belong to any branch so just use git checkout -b <new-branch>
If you haven't already committed your changes, just use git checkout
to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.
If you have already committed your changes:
git log
and remember the SHA of the commit you want to move.git cherry-pick SHA
substituting the SHA from above.git reset HEAD~1
to reset back before your wrong-branch commit.cherry-pick
takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With