Git How-To: Remove Your Password from a Repository

Published on .

When you’re making an app that uses credentials to access some service, in the early stages of development before any code to access a config-file is written, a username and password are occasionally hard-coded in the source.

Since you use version control like all good developers, it’s possible these hardcoded credentials get committed. This poses a grave security risk, especially if you want to open source the code including the repository.

Here’s how to remove a password from any file, in all revisions, in a git repository:

$ git filter-branch --tree-filter "find . -type f -exec sed -i -e 's/originalpassword/newpassword/g' {} \;"

Just replace originalpassword with the word you want to replace, and newpassword with the word you want to replace it with

Here’s another handy one, deleting all the lines containing word:

$ git filter-branch --tree-filter "find . -type f -exec sed -i -e '/$*word/d' {} \;"

After you’re done, you can check if your password really isn’t in any of the files anymore by grepping every revision ((By OR-ing with true we make sure the command is run in any revision, because if it returns false (e.g. originalpassword isn’t found in any of the files of a specific revision), git will think the filter failed and it won’t check the other revisions. You’ll notice if this happens since you’ll get a “tree filter failed” error on the first nonmatching revision.)):

git filter-branch --tree-filter "grep -r originalpassword * || true"

If you’re positive the changes were done correctly, make sure to remove the automatically created backupfiles in refs/original/ ((If you don’t, sooner or later you’ll get the following error message:

Cannot create a new backup.
A previous backup already exists in refs/original/
Force overwriting the backup with -f


Now enjoy a fine glass of wine, safe in the knowledge that your repository won’t reveal any of your secrets.

David Verhasselt

Senior full-stack engineer with 5 years of experience building web applications for clients all over the world.

Interested in working together?

Find out what I can do for you or get in touch!

Like this? Sign up to get regular updates