henriquehbr.xyz

Blog Supporters Resume
Part time open-sourcerer, Linux enthusiast, Rust fanatic

Revert initial Git commit

October 24, 2021 — (Last edited on February 13, 2022)

Problem

Let’s suppose you have a repository with the following commit history:

5a998b8 (HEAD -> main) third commit
f318ad8 second commit
a187c18 first commit

By default, when you try to reset all commits of a given repository by running:

git reset --hard HEAD~3

The following error message will be shown:

fatal: ambiguous argument 'HEAD~3': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Solution

You can delete the HEAD and restore your repository to a new state, where you can create a new initial commit:

git update-ref -d HEAD

After you create a new commit, if you have already pushed to remote, you will need to force it to the remote in order to overwrite the previous initial commit:

git push --force origin

Special thanks