Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the last n commits on Github and locally?

Tags:

git

github

commit

I'm trying to delete the last 2 commits from one of my GitHub repositories. I've tried as suggested here : git push -f origin HEAD^^:master. It seems that it works, as the last two commits are removed.

Then I deleted them from my local repository with git rebase -i HEAD~2. I remove the lines that are related to those commits, and check with git log that they are correctly removed.

After that, I make some changes in my local repository, make a new commit, and push to GitHub. The problem is that, in my GitHub account, I have the previous two commits that I've tried to delete.

I think the problem is in my local repository, because if I clone my Github repository to my local and make some changes here, when I push a new commit those old commits aren't pushed to GitHub.

like image 658
Ivan Fernandez Avatar asked Oct 06 '22 17:10

Ivan Fernandez


People also ask

How do I delete all commits locally?

If your excess commits are only visible to you, you can just do git reset --hard origin/<branch_name> to move back to where the origin is. This will reset the state of the repository to the previous commit, and it will discard all local changes.

How remove last commit locally remotely?

To undo the last commit from a remote git repository, you can use the git reset command. command. This will undo the last commit locally. command to force push the local commit which was reverted to the remote git repository.

Can you delete commit history in github?

Typically, you should never delete your commit history. However, if you're working on your own project or a repository that isn't used by many people, you might want to delete your commit history without touching the code.


3 Answers

To remove the last two commits locally I'd suggest using:

git reset --hard HEAD^^

Rebase is a completely different operation that won't help you here.

like image 182
KL-7 Avatar answered Oct 16 '22 09:10

KL-7


If you want to remove the 2 (two) last commits, there is an easy command to do that:

git reset --hard HEAD~2

You can change the 2 for any number of last commits you want to remove.

And to push this change to remote, you need to do a git push with the force (-f) parameter:

git push -f

However, I don't recommend to do any git command with -f or --hard options involved if there are new commits on remote (Github) after this commits that you want to remove. In that case, always use git revert.

like image 40
Dherik Avatar answered Oct 16 '22 10:10

Dherik


The following works for me

git reset HEAD~n

It removes the last n commits from local repo, as HEAD^ removes only one. If you need to remove these changes from remote, you might need to force push as you will be behind remote.

git push -f origin <branch>
like image 53
Sial01 Avatar answered Oct 16 '22 10:10

Sial01