Is it possible to set environment variables while using nix-shell which gets invoked via a shebang? For example, I'm using
#! /usr/bin/env nix-shell
#! nix-shell -i runghc --pure
and would like to set an environment variable like FOO=bar
. Note, FOO
is not necessarily defined by the surrounding environment. Thus --keep FOO
is not an option.
Looks like you're using an accompanying shell.nix
file. You could simply define your environment variable as a derivation attribute there.
shell.nix
pkgs.mkShell {
buildInputs = [ pkgs.ghc ];
shellHook = ''
VIA_SHELL_HOOK=it\ works # no it doesn't
'';
VIA_DRV_ATTR = "working";
}
Example executable script
#!/usr/bin/env nix-shell
#!nix-shell -i runghc --pure
import System.Environment(getEnv)
main = do
getEnv "VIA_DRV_ATTR" >>= print
getEnv "VIA_SHELL_HOOK" >>= print
Output:
"working"
hello: VIA_SHELL_HOOK: getEnv: does not exist (no environment variable)
(Nix 2.3.4, Nixpkgs 20.03)