Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move unpushed committed code to another branch?

Tags:

git

So I have the following situation:

I committed some work locally, without pushing to the remote repository. I want to move this local code to another branch, because if I pull, there will be modifications that will ruin all the work I put locally.

This is the output of git status on the old branch:

On branch <branch_name> Your branch is ahead of 'origin/<branch_name>' by 1 commit.   (use "git push" to publish your local commits) nothing to commit, working directory clean 

And this is the output of git status on the newly created branch:

On branch <branch_name> nothing to commit, working directory clean 
like image 627
Narcis Neacsu Avatar asked Jul 20 '17 13:07

Narcis Neacsu


People also ask

How do I move multiple commits from one branch to another?

You can do this with multiple commits too, just cherry pick several, then reset back to the last commit you want to keep. The process is the same if you have committed to local master by mistake - just cherry-pick to a branch, then reset master.


2 Answers

If it's just one commit, you can simply do

git reset HEAD~1 git stash git checkout anotherbranch git stash pop 

And if you want to put it in a fresh new branch, another way is

git branch newbranch git reset --hard HEAD~1 
like image 111
j4nw Avatar answered Oct 15 '22 12:10

j4nw


If you made the branch after you committed it should contain the commit that you are wanting to move. You can verify this with git log, you should see your commit as the first on in the log.

On the branch that you no longer want the commit to be do git reset --hard HEAD~. This removes the commit from the branch and reset the branch so that you can now pull without any issue. (Be sure that your commit is on the other branch as after doing this your commit will be gone).

If the commit is not on your other branch, you can either delete the branch and create it again from the original branch with git checkout -b <branch name> or you can cherry-pick it into your branch with git cherry-pick <SHA of your commit> which will make a copy of the commit on your branch. Then you can reset the original branch with the steps above.

like image 21
Schleis Avatar answered Oct 15 '22 12:10

Schleis