How to delete commit from a branch in Git?

6

How can I delete commit from a branch ?

I made an attempt to delete a commit that I did not want, but I ended up making the situation even worse. I'm afraid to do something wrong.

Git tells me to use git reset --hard HEAD , but I'd like to confirm before doing so to get everything right.

    
asked by anonymous 15.05.2016 / 02:27

2 answers

6

This is essentially almost the same if you want to delete the current commit . You probably want to go back to the previous commit , so you need to get the current

git reset --hard HEAD~1

If you want to go back to some other specific commit it should use hash . Or in some cases you can do

git reset --hard HEAD^

Try with --soft before and see if it solves what you need. It is less radical and more secure.

If commit has already been sent you will have to force on the remote:

git push origin HEAD --force

This will cause all local changes to be lost. So if you can not lose them, I suggest doing a stash with all of them before.

If it goes wrong it can revert like this:

git reset HEAD@{1}

If you're scared to do something wrong, make a backup before and you can go back to the original if you did not quit as you expected.

If you want to do on the remote:

git push origin +HEAD^:master #ou outro nome aqui

If fear extends to the remote server, do the same with it. If you involve the remote server, various care needs to be taken, the main thing is that your current branch should be the newest of the remote. If this is not guaranteed, you will be creating an alternate reality for other users.

Read recommended .

    
15.05.2016 / 02:57
0

The permanent deletion of one (1) commit can be done by the following command:

 git reset --hard HEAD~1

You can replace 1 with the number of commits you want to remove.

If this commit is also in the remote branch (GitHub, Gitlab, etc.), you need to apply the force command ( -f ) to make push to the remote branch:

git push -f

However, I do not recommend to apply any command with the options -f or --hard if:

  • There are new commits after this commit that you want to remove.
  • There are new branches created from this commit removed from this same branch.

In this case, first try using git revert .

    
24.07.2018 / 18:31