Yes, it's possible to set environment variables when utilizing nix with shebang.
nix as main language in a single file with bash shebang
#! /usr/bin/env -S bash -c 'nix-shell --pure $0'
with import <nixpkgs> {};
let
haskellCode = ''
import System.Environment (getEnv)
main = do
getEnv "VIA_DRV_ATTR" >>= print
getEnv "VIA_SHELL_HOOK" >>= print
'';
in
mkShell {
buildInputs = [ ghc ];
shellHook = ''
export VIA_SHELL_HOOK="VIA_SHELL_HOOK works"
exec runghc <<< '${haskellCode}'
'';
VIA_DRV_ATTR = "VIA_DRV_ATTR works";
}
$ ./test.nix
"VIA_DRV_ATTR works"
"VIA_SHELL_HOOK works
The drawback is that haskell code gets embedded in a nix string.
haskell (or any other) as main language in a single file with nix shebang
#! /usr/bin/env nix-shell
#! nix-shell -i runghc --pure -E "with import <nixpkgs> {}; mkShell { buildInputs = [ ghc ]; VIA_DRV_ATTR = \"VIA_DRV_ATTR works\"; shellHook = ''export VIA_SHELL_HOOK=\"VIA_SHELL_HOOK works\"''; }"
import System.Environment (getEnv)
main = do
getEnv "VIA_DRV_ATTR" >>= print
getEnv "VIA_SHELL_HOOK" >>= print
$ ./test.hs
"VIA_DRV_ATTR works"
"VIA_SHELL_HOOK works"
The drawback is the lengthy shebang nix-shell line with escaped quotation marks. There doesn't seem to exist a way to break it into several lines.
both nix and another language in a single file with shebang?
Maybe it's possible to compose 2 language blocks one after another and write some generator script in shebang line in the manner of combining bash and haskell.