DEV Community

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

Posted on

2 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️