How to delete a wrongly-checked-in file from the Git history

published Jul 23, 2025

A quick set of commands to run.

How to delete a wrongly-checked-in file from the Git history

The following commands will delete from the current branch a particular file or a folder that was wrongly committed, then vacuum the history to completely delete all references of it.  For more advanced use cases (e.g. delete a file from all the Git repo's history), check out git-filter-repo instead.

# The following code assumes you are in the master branch.
# Adjust accordingly if that isn't the case.

# First, stash any unchecked files.
git stash --include-untracked
# Now delete the file from the history. You can specify globs and double-quoted paths. git filter-branch --index-filter 'git rm --cached --ignore-unmatch -r path/to/delete "quoted path that has/spaces"' # Recover the stash.
git stash pop
# Delete the backup of the ref. git update-ref -d refs/original/refs/heads/master
# Expire all unreachable references. Note that if other branches, remote or local,
# still contain references to the undesired files, this will not actually remove
# the deleted files from the actual Git repository content. git reflog expire --all --expire-unreachable=now
# Finally, garbage collect all references that are gone. git gc --aggressive --prune=now

And that's all!