Manipulating history is very common for developers who work with Git regularly. Indeed, developers often need to remove commits from the Git history. Luckily, Git provides many commands to make this operation possible.
Let’s get to it 😎.
Before manipulating the Git history, ensure that your working directory is clean of any changes using the git status command.
To delete commits from a remote server, first, you will need to remove them from your local history.
If the commits you want to remove are placed at the top of your commit history, use the git reset --hard
command with the HEAD
object and the number of commits you want to remove.
git reset --hard HEAD~1
This command will remove the latest commit.
git reset --hard HEAD~3
This command will remove the latest three commits.
You can also remove up to a specific commit using a commit’s hash, like so:
git reset --hard <hash>
If, however you want to remove non-consecutive commits, you’ll need to use an interactive rebase.
git reflog
command.git rebase -i <hash>
.git rebase --continue
or start over by aborting the rebase.To delete commits from remote, you will need to push your local changes to the remote using the git push command.
git push origin HEAD --force
Since your local history diverges from the remote history, you need to use the force
option.
As you can see, Git makes it easy to delete commits from a remote server.
However, you need to be careful when using the git push
command with the force
option because you could lose progress if you are not cautious.
Thank you for reading!