Search code examples
nixnixpkgs

nix-shell: how to load environment variables from env file?


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?


Solution

  • 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.