Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving changed files to another branch for check-in

Tags:

git

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?

like image 365
mainsocial Avatar asked Aug 27 '11 22:08

mainsocial


People also ask

Can I move my changes to another branch?

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.


2 Answers

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>

like image 194
Bill Door Avatar answered Oct 20 '22 03:10

Bill Door


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:

  1. Type git log and remember the SHA of the commit you want to move.
  2. Check out the branch you want to move the commit to.
  3. Type git cherry-pick SHA substituting the SHA from above.
  4. Switch back to your original branch.
  5. Use 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.

like image 26
Amber Avatar answered Oct 20 '22 04:10

Amber