How To Delete File on Git

When working with Git, it is quite common for developers to add many files to their repository, just to realize that they want to delete them later on.

Deleting files on Git is often a source of confusion : do I need to delete them from my repository or should I delete them from the filesystem?

If you introduced a file in previous commits, is there a way for you to delete this file from all the commits in the repository?

In this tutorial, we are going to see how you can easily delete files on Git, whether it is only from your Git repository or from the filesystem.

Table of Contents

HEAD (as a reminder, HEAD is the last commit of your repository).

In this case, the Git command to be executed is the “git rm” command we described earlier.

$ git filter-branch --force --index-filter --prune-empty "git rm --cached --ignore-unmatch <path_to_file>" HEAD

As the command is quite complex, let’s have a breakdown of all the options used :

  • –force : quite self-explanatory, it forces the filter-branch to start even if it may not want to (given the documentation because it can contain temporary directories)
  • –index-filter : option used in order to rewrite the index, exactly what we want in the case of a file deletion
  • “git rm” command : the command to be executed on all branches, revisions and commits matching in the history, in this case it will remove the file from the repository and ignore files that don’t match
  • –prune-empty : avoid having empty commits in the repository with zero files, this option will prune commits automatically

In this case, let’s say that we want to delete the file “file1” contained in our repository.

We are going to execute the following command.

$ git filter-branch -f --prune-empty --index-filter "git rm -r --cached --ignore-unmatch ./file1" HEAD
delete files from entire git history using filter branch

This command can take a while, if your history contains many files, but in the end, the deleted file won’t be in your Git history anymore.

You can check with a “git log” command, but the commits linked to the deleted file should be pruned if necessary.

Conclusion

In this tutorial, you learnt how you can easily delete a file from a Git repository, whether you want to delete it from the filesystem or not.

You also learnt that it is completely possible to delete a file from an entire Git repository using the “filter-branch”.

Deleting files in Git is linked to file restoration, as a consequence, you may be interested with the following resources :

If you are interested in software engineering, we have a complete section dedicated to it on the website, so make sure to check it out.

Icons made by Smashicons from www.flaticon.com

Posted by Contributor