🇩🇪 Deutsch 🇬🇧 English

28 May 2024

git: Remove a file from repository

How can one delete a file from a Git repository?


You can do this using git rm:

git rm unwanted-file.txt

This command will delete the file and stage its deletion to be included in the next commit. If we want to remove a directory, we must include the -r (recursive) flag, as with the standard rm command.

Note that any files removed this way will still be visible in previous commits. If the file we want to remove contains sensitive content, we will need either to create a new Git repository with a fresh history or to rewrite the history of our current repository using git filter-branch:

git filter-branch -f --index-filter 'git rm -rf --cached --ignore-unmatch unwanted-file.txt' HEAD

Rewrite 6ed1...fb58 (3/12) (0 seconds passed, remaining 0 predicted)    rm 'unwanted-file.txt'
[...]

Note that rewriting the commit history in this way is dangerous and will permanently alter your repository. Additionally, git filter-branch is a slow operation, especially for large repositories with many commits. Double-check that the name of the file to be removed is correct before running this command.

After our commit history has been rewritten, we will need to force push the changes to remote repositories using a command such as the following:

git push --force

[...]
remote: . Processing 1 references
remote: Processed 1 references in total
 + 3147f29...52aebb6 main -> main (forced update)
Schauen sie doch auch mal auf einen Sprung bei atac vorbei!