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
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.
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
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.
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