Search code examples
gitgitignore

How can I ignore the .env file in git?


I made changes in my .env file and wrote after that in terminal git status:

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    modified:   .env

I would like that the changes in the .env file be igonored by git so I added this line in .gitignore:

/.env

Now when I write git status I get the result:

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    modified:   .env
    modified:   .gitignore

What can I do now? Why is gitignore not ignored?


Solution

  • The problem with a git rm --cached .env (which would enable to .gitignore to operate) is that, once committed and pushed, everybody lose the file on their next git pull.

    If you need to have local .env settings (that should not be part of your Git repository), you can either:

    • check if your .env comes with some kind of #include directive, which would allow you to include a second file .env.local (that you can add safely to your .gitignore)
    • or setup a merge content driver, and version only .env.tpl (a template file), while ignoring .env itself (so using the git rm --cached .env, but with a git add .env.tpl)

    The idea behind a content filter driver is to generate automatically on git checkout/git switch the .env file, based on the .env.tpl template file and a local (and ignored) .env.values value file.
    See "Github private repo - manage packages for different environment" as an example of such an approach.