When we commit a file to a git system (such as, Azure DevOps or GitHub) it shows up in the folder structure of the repo.

And also, there is a record created in the underlying history structure.

We can delete the file that needs to be confidential, after we accidentally commit it.

But it'll stay in the commit history of the git system.

And anyone who can access the git system, can search through the commit history and find that file.

To delete a file from the git system, we can use the following command;

FILE_PATH_AND_NAME="src/backend/.env"

git rm -rf --cached --ignore-unmatch ${FILE_PATH_AND_NAME}

But, it'll not remove the file from the commit history. To remove it from the history as well, we can use the following command;

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch ${FILE_PATH_AND_NAME}" HEAD

This command will delete the file from the commit history and re-write the commit history without it.

It may take so long to complete, regarding the size of the commit history of the repo. To give a scale, it may need almost a full hour if you have 10K commits and wanted to remove a file from one of the first commits.

After the command finishes, we just need to commit the changed history, by executing the following command;

git push --force

References