Removing a File from Git History¶
Sometimes you need to wipe all traces of a file from a Git repo.
You may need to do this if you accidentally add and commit a large file, or if you add a file that contains personal information.
There is a tool made for this called git filter-repo
.
Installing git-filter-repo
¶
Or, install manually via Python's pip
:
Removing the File¶
Optionally, make a backup just in case.
Then use filter-repo
--path path/to/file
: The file you want to remove--invert-paths
: Inverts filtering logic, which means everything except the specified file is kept.
Then force push (if your unwanted file is in the remote repo).
This step is optional, but cleans up old references so that nothing is referencing the deleted file.
Using git filter-branch
¶
This is considered deprecated, but it still works. This tool is already built into git, and does not require any additional tools to be installed.
git filter-branch --force --index-filter "git rm --cached --ignore-unpatch path/to/file" \
--prunce-empty --tag-name-filter cat -- --all
Note: This method only removes the file from the branch you're currently on.
Using git rebase
¶
You can use rebase
for this. This method could be easier if you just need to work with
recent commits.
Find the commit hash where the file was added:
Interactively rebase to remove the commit:
- Change
pick
toedit
for the commit that added the file.
Remove the file and amend the commit:
Then continue the rebase process:
Then force push (if your unwanted file is in the remote repo).