How Do You Remove a File from a Git Repository so the Old Versions Are Eliminated?

Problem scenario
You accidentally uploaded a file with sensitive data (e.g., hard-coded credentials such as a database username and password) to a Git repository.  You want to eliminate it from the Git repository so all of its history are removed from the previous commits and it is unretrievable.  How do you do this?

Solution
WARNING:  This will delete data.  Some people rely on Git repos as a disaster recovery product.  Only do this if you know what you are doing or if the Git repo is not that important and can be restored from somewhere else.

1.  Change directories to be in the Git repository:  cd /path/to/git/nameOfrepo

2.  Remove the file that needs to be removed:  git rm filename

3.  Run this command:

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch subdir/path/foobar.txt' --prune-empty --tag-name-filter cat -- --all

# Replace "subdir/path" with the path from the Git repo to where the file is that needs to be eliminated.  This is relative to the directory you are currently in.  If the file is not in a subdirectory of the Git repo, you will not have anything for "subdir/path" -- not even a slash.

# Replace "foobar.txt" with the name of the file you want eliminated.

# If you receive an inexplicable error, try to do step #4 first, then do step #3.

4.  Run this command:  git commit -m "Eliminated a file"

5.  Run this command:  git push origin --force --all

6.  Run this command:  git push origin --force --tags

7.  There are strategies to avoid accidental commits.  The gitignore file may help you.  To learn more, see this link.

If you want a list of books on Git, see this link.

Leave a comment

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