[git] How to un-commit last un-pushed git commit without losing the changes

Is there a way to revert a commit so that my local copy keeps the changes made in that commit, but they become non-committed changes in my working copy? Rolling back a commit takes you to the previous commit - I want to keep the changes made but I committed them to the wrong branch.

This has not been pushed, only committed.

This question is related to git

The answer is


If you pushed the changes, you can undo it and move the files back to stage without using another branch.

git show HEAD > patch
git revert HEAD
git apply patch

It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.


For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.

  1. Go to Version control window (Alt + 9/Command + 9) - "Log" tab.
  2. Right-click on a commit before your last one.
  3. Reset current branch to here
  4. pick Soft (!!!)
  5. push the Reset button in the bottom of the dialog window.

Done.

This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.


With me mostly it happens when I push changes to the wrong branch and realize later. And following works in most of the time.

git revert commit-hash
git push

git checkout my-other-branch
git revert revert-commit-hash
git push
  1. revert the commit
  2. (create and) checkout other branch
  3. revert the revert

PLease make sure to backup your changes before running these commmand in a separate folder

git checkout branch_name

Checkout on your branch

git merge --abort

Abort the merge

git status

Check status of the code after aborting the merge

git reset --hard origin/branch_name

these command will reset your changes and align your code with the branch_name (branch) code.


2020 simple way :

git reset <commit_hash>

Commit hash of the last commit you want to keep.