lksdfjöalksdjf
lksdfjöalksdjf

Reputation: 91

Nix: Can an installed package set a user environment variable?

I would like to define rc-files of my software via Nix. Therefore I define a new package in config.nix which will contain a config file:

{ pkgs, ... }:
{
packageOverrides = pkgs : with pkgs; {
  custom-config = import ./custom-config {
    inherit (pkgs) stdenv;
  };
};
}

Then in custom-config/default.nix the file is defined inline:

{ stdenv }:

stdenv.mkDerivation rec {
  name = "custom-config";
  stdenv.mkDerivation {
    name = "CustomConfig";
    src = builtins.toFile "customrc" ''
      # content
      '';
  };
}

The last part missing is: Add a specific environment variable to the users default shell, like CUSTOM_CONFIG_RC, which is honored by to relevant program.

Can anybody give me a hint? I am just starting to grasp the language.

Upvotes: 8

Views: 3410

Answers (1)

Chris Martin
Chris Martin

Reputation: 30756

The typical Nix way is to do this without modifying the user's shell, and instead use makeWrapper to wrap the program that uses the RC file. That way your environment doesn't need to get polluted with variables that only one program needs.

buildInputs = [ makeWrapper ];

postInstall = ''
  wrapProgram "$out/bin/my-program" --set CUSTOM_CONFIG_RC "$rcFile"
'';

See more examples of makeWrapper use in the Nixpkgs repo.


If you really do want that variable available in your environment, your derivation could do something like

postInstall = ''
  mkdir -p $out/share
  echo "export CUSTOM_CONFIG_RC=$rcFile" > $out/share/your-rc-setup-script.sh
'';

When the package is installed, this will end up symlinked from ~/.nix-profile/share/your-rc-setup-script.sh, and then in your .bashrc, you can load it with

source $HOME/.nix-profile/share/your-rc-setup-script.sh

Upvotes: 11

Related Questions