I am working on an angular project and mistakenly commits the environment files that have some apikeys on it. It has been after a couple of commits that I noticed that I accidentally committed the env files. What I did was just to add the files in the .gitignore file, then continued with my daily chores. And then today, as I was fixing a bug, I checked out some previous commits in a detached state just to inspect where was an existing bug introduced then when I got back to the main using:
git checkout main
The environment files are all missing.
I was able to restore the files from the commits until I ignored the file by this:
git rev-list -n 1 HEAD -- src/environments
However, this was a previous version and the environment files were already changed heavily after this.
Adding the environment files to .gitignoreprevents future commits, but doesn’t remove them from Git history — so when you git checkout main, Git removes them from your working directory because they’re no longer tracked.
Since you’ve modified the environment files after they were ignored, and didn’t commit those changes, they’re gone unless you have a backup.
How to fix:
1.Recover the last committed version (before they were ignored):**
git checkout <commit-id> -- src/environments
2.(You already did this.)*
3. If you edited the env files after ignoring them (but never committed), those changes are lost unless:
You saved them somewhere else (e.g. stash, backup, IDE local history).
Or they are in your file system but untracked — check:
bash
CopyEdit
git status
If they’re listed under “Untracked files”, you can just re-add them.
4. To prevent future loss, do this:
Restore the correct versions of your environment files.
Keep them in .gitignore.
Add them to a secure backup or use a .env file pattern.
Never rely on Git for secrets — use environment variables or secret managers.
Summary:
You lost your latest uncommitted changes to the environment files when switching branches because Git stopped tracking them after you added them to .gitignore. To recover, you’ll need to restore from a previous commit or backup.