DEV Community

Cover image for Removing secrets from a git repo
Sunny Golovine
Sunny Golovine

Posted on

Removing secrets from a git repo

Working on Awesome Devtools this past week, I decided to make the repo public so others could contribute to it. I had one slight problem though, I had committed my .env file which contained secrets I would rather the world not know.

So how would you delete a file like this? Well standard logic says just....delete it. But with git it's not that simple, when you delete something, even though the latest version of your code no longer has this thing, the previous version of your code still do. Simply deleting the file would not work.

There are two ways of deleting a file entirely in git. One way where you preserve your git history, and one where you do not.

Delete while preserving git history

If you want to delete a file while still preserving your git history, you can do so with a neat recipe from Github.

# Delete the file
git rm --cached <your_file>

# Commit the change
git commit --amend -CHEAD

# Push the commit
git push

Enter fullscreen mode Exit fullscreen mode

Delete the file and nuke git history

If you're like me and don't really care about your git history for a particular project, you can do it the way I did it and just nuke the file and all the history leading to the file.

First run git remote -v to get your current remote.


➜ git remote -v
origin  git@github.com:sgolovine/awesome-devtools.git (fetch)
origin  git@github.com:sgolovine/awesome-devtools.git (push)

Enter fullscreen mode Exit fullscreen mode

Now delete your the file and also delete the .git folder. Once you've deleted the file, recreate the git repository locally


git init
git add -A
git commit -m "Initial Commit"
git remote add origin <url from step 1>

Enter fullscreen mode Exit fullscreen mode

Finally do a force push to your remote to overwrite the previous history with git push -f

That's it! If you know of a better way to delete a file from git history, leave a comment below and I will update the article. You can find more of my article here and on my blog

Top comments (0)