3

Related to this question: nix-shell: how to specify a custom environment variable?

With this derivation:

stdenv.mkDerivation rec {
  FOO = "bar";
}

FOO will be available in the nix shell as an environment variable, but is it possible to load environment variables from an env file?

Robert Hensing
  • 4,412
  • 13
  • 18
José Luis
  • 3,152
  • 3
  • 26
  • 31

1 Answers1

3

You could use nix-shell's shellHook to load environment variables from a file by sourcing them as shell code. For example:

stdenv.mkDerivation {
  name = "my-shell";
  shellHook = ''
    # Mark variables which are modified or created for export.
    set -a
    source env.sh
    # or to make it relative to the directory of this shell.nix file
    # source ${toString ./env.sh}
    set +a
  '';
}

You could switch from stdenv.mkDerivation to mkShell if your shell isn't also a package.

Robert Hensing
  • 4,412
  • 13
  • 18
  • Almost, in my case should be `set -a; source .env; set+a`, since in a .env file you don't explicitly export the variables. Other problem is that it doesn't work in combination with direnv – José Luis May 05 '20 at 07:36
  • Thanks! I've added it to my answer. But what's the problem with direnv? You could change `env.sh` to `.envrc` if you want to load its file. Was direnv part of the question? – Robert Hensing May 05 '20 at 18:20
  • `direnv` was not part of the question, I should create another question for that, but I was confused because the variables were not loaded by `direnv`. Not sure what is the problem, but while with `nix-shell` it works, with `direnv` + `lorri` I get this error (running `lorri shell`): `/nix/store/...-stdenv-linux/setup: line 83: /home/myuser/direnv-test/env.sh: No such file or directory`. I solved it replacing `source ${toString ./env.sh}` with `source ${./env.sh}` – José Luis May 06 '20 at 10:34
  • 1
    `lorri` runs the `shellHook` inside the Nix sandbox, so that makes sense. `${./env.sh}` puts the env file in the Nix store so it is available. `${toString ./env.sh}` used the file in place so that `$0` and `${BASH_SOURCE[0]}` worked as usual in `nix-shell`. That doesn't seem feasible with `lorri`. – Robert Hensing May 07 '20 at 15:24