Provide environmental variables from nix

Hi all,

I got a question that I tried to search on Google for a lot of time without much success.

I considering to introduce nix at my workplace, the need is to provide a shell with several environment variables pointing to the right (nix) directories.

Think about a variable for a compiler, other for the libraries, etc.

When I talk about libraries directory I think about FOOBARLIB_ROOT=/nix/…/foobar

I have around 50 of those variables to be set for environment.

Can this be accomplished easily? Especially without re-writing every recipe, but hopefully just wrapping existing recipes. Where I should look first?

Yes, this is trivial. Typically you would write a Nix expression for your project to perform the build with Nix. This automatically gives you an environment you can use with nix-shell for development.

An alternative is to write an expression just for use with nix-shell. It is customary to call this file shell.nix. I could recommend using the mkShell function then.
https://nixos.org/nixpkgs/manual/#sec-pkgs-mkShell

You could then do something like:

with import <nixpkgs> {};
mkShell {
  # this will make all the build inputs from hello and gnutar
  # available to the shell environment
  inputsFrom = [ hello gnutar ];
  buildInputs = [ gnumake ];
  MY_ENV_VAR = "foo:bar";
}

All arguments are passed on as environment variables eventually.


Just to add. If you want to point to the Nix store, then you should point to the derivations, that is, like in the above example, you refer to e.g. gnumake. In this case gnumake is added as a build input, so it will be on PATH and other relevant environment variables will be automatically set.

1 Like

Adding a small example of a variable that points to something in the Nix store:

with import <nixpkgs> {};

stdenv.mkDerivation rec {
  name = "some-env";

  buildInputs = [
    boost
  ];

  BOOST_ROOT = "${boost}/lib";
}
$ nix-shell
$ echo $BOOST_ROOT
/nix/store/5w298gaixjkfs18w51p7y35v105rgdfw-boost-1.67.0/lib
3 Likes