remove file from git history

Git Remove File from History

Sometimes you may need to remove one or more files from your git repository’s history. It is relatively easier to simply remove the file from your repository and commit changes but removing the file from history can be very tricky. In this article, we will learn how to remove a file from git history. Please make sure you backup your entire repository before you follow these steps below. Also, if you have recently committed the file and made one to two changes to it, then it is advisable to simply undo those commits, remove the file and redo the commits. That is much more preferable than deleting file from commit history. If you try to remove file from git history, using the following steps, it will result in a large number of commits, and may also result in divergence. So be careful before you proceed further.


Git Remove File from History

Here are the steps to remove file from git history. Run the following command to remove file from git history. Replace path_to_file with the path to file that you want to remove.

$ git filter-branch --index-filter \
    'git rm -rf --cached --ignore-unmatch path_to_file' HEAD

If the above command does not work for you, then you can try the following.

$ git filter-branch --tree-filter 'rm -f <path_to_file>' HEAD

Alternatively, you can use a third-party tool filter-repo to delete file from git repository. It is a third-party tool and needs to be installed first, using the following command.

$ pip3 install git-filter-repo
$ git filter-repo --path <path to the file or directory> --invert-paths

Once you have verified all the changes, it is time to push them to remote branches.

$ git push origin --force --all

In this article, we have learnt how to delete file from git repository.

Also read:

Bash Loop Through Files in Directory Recursively
How to Remove .pyc File from Git Repository
How to Reset Git Local Repository to Remote
What to Do If You Cannot Access NGINX from Outside Your Network
How to Undo Git Rebase

Leave a Reply

Your email address will not be published. Required fields are marked *