How do I delete commit from a branch in Git?

Asked

Viewed 22,374 times

14

How can I exclude commit of a branch?

I made an attempt to try and delete one commit I didn’t want to, but I ended up making the situation worse. I’m afraid to do something wrong.

Git tells me to use git reset --hard HEAD, but I’d like to confirm before I do it to make it all right.

2 answers

14


It’s essentially almost that even if you want to delete the commit current. Probably what you want is to return to commit previous, then need to catch the current - 1:

git reset --hard HEAD~1

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

git reset --hard HEAD^

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

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

git push origin HEAD --force

This will make you lose all local changes. So if you can’t lose them, I suggest making a stash with all of them before.

If it goes wrong, you can reverse it like this:

git reset HEAD@{1}

If you’re afraid to do something wrong, do one backup before and can return to the original if it does not turn out as expected (in general this should not be necessary because the purpose of this tool is precisely this, but we know how it is...).

If you want to do it on the remote:

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

If fear extends to the remote server, do the same to it. If involve the remote server, various precautions need to be taken, the main thing is that your branch current must be the newest of the remote. If this is not guaranteed, it will be creating an alternative reality for other users.

Recommended reading.

3

Permanent deletion of a (1) commit can be done by the command below:

 git reset --hard HEAD~1

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

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

git push -f

However, i do not recommend 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 branchs created from this commit removed from this same branch.

In this case, try using the git revert.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.