gitrepo

To undo the last git commit push or the last 2


How do we undo the last git commit push or the last 2 pushes, by the easy reference that number ? i.e. for example something like

git revert -n1
git revert -n2
git reset -n2

I'm quite git noob. Thanks


Solution

  • The answer to this depends a lot on what exactly you want, but I'll give you some general information.

    To actually undo a commit, you can use git reset. This will take your branch's HEAD and put it where it was 2 commits ago, keeping you files as they are now:

    git reset HEAD~2 --soft
    

    If you want the files to go back to how they were, you can use --hard:

    git reset HEAD~2 --hard
    

    Now, this is a bit problematic if you've already pushed your commits, because Git is supposed to only have commits added - never removed. So if you try to push a previous commit, you will receive an error saying you are behind the remote.

    If you are sure you want that, you can force the change in the history by passing --force to git push. This can create a problem if you are collaborating with other people though: when they try to pull, if they already had the commits you are deleting, they will receive an error too, and will need to pass --force to git pull.

    To allow reverting things without changing the commit history, git revert exists: it creates a new commit which does the opposite the reverted commit did. This will leave the changes in the commit log, but the actual files will be as they were before. If you want this, you can run:

    git revert HEAD~2..HEAD
    

    This will create reversal commits for HEAD (your last commit) and HEAD~1 (your second to last commit), leaving the files as they were 2 commits ago. If you want to revert just a single commit, you can specify only that one. To revert just the latest commit you can use:

    git revert HEAD