To revert the initial commit, use the command below.
git update-ref -d HEAD
Once done, the uncommitted files are now in the staging area. You can confirm this staging status by the git status
command and you'll get a result similar to the one in the screenshot linked below.
My uncommitted files in the staging area are in yellow color
Git suggests the syntax of the command to unstage the files in question (see the image above). In short use the command below:
git rm --cached . -r
The dot(.
) in the command represents the current location/dir while the flag -r
unstages the files recursively without prompting confirmation for each file.
You can now perform a quick git status
to confirm that the the staging area is now empty.
If you had already pushed your files to a remote repo, the next step is pushing these changes to the remote repo to restore parity between the two (local & remote).
However, before pushing, create a .gitignore
file and populate it with the unnecessary files. Read how to create a .gitignore
file here.
At this juncture, the next best logical solution is pushing the changes to remote either with git push
or git push -f
(However, always remember force pushing is dangerous - read here.).
However, both of these push commands could return an error, that may require one to pull and resolve merge conflicts. So in my bid to avoid this trouble, you might just have to delete the entire remote repo (On GitHub with these instructions), then recreate it with the same name.
In addition:
- Delete the local git repo using the
rm -rf .git
,
- re-initialize it with
git init
,
- add all the current files to the staging area with
git add -A
,
- commit them with
git commit -m "<commit message>"
,
- add the remote origin URL with
git remote add origin <repo url>
,
- and finally, push the local files once more with
git push -u origin main
.
PS:
There are many reasons to revert the first commit. However, I think one of the most common reasons that equally affected me is forgetting to add a .gitignore
file that excludes unnecessary files from a commit. In my case, this mistake meant that I unintentionally pushed node_modules directory to the remote repository.
After further research, I found a technical article explaining a simpler method of Ignoring a Previously Committed File, that does away with the need to undergo the tedious process of uncommitting and having to delete the remote repo.
git status
, and to my surprise, git saidfatal: Not a git repository (or any parent up to mount point ...)
! – Bellied