Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nix-shell: how to specify a custom environment variable?

Tags:

nixos

I'm learning about nixos and nix expressions. In a project folder I created a shell.nix and I when I run nix-shell I want it to preset an environment variable for me. For example to set the PGDATA env var.

I know there are several ways to write nix expression files (I'm not yet used to most of them). Here is my sample:

shell.nix

let 
  pkgs = import <nixpkgs> {};
  name = "test";
in pkgs.myEnvFun {
  buildInputs = [
    pkgs.python
    pkgs.libxml2
  ];
  inherit name;
  extraCmds = ''
    export TEST="ABC"
  '';
 }
like image 562
monk Avatar asked Dec 30 '14 22:12

monk


People also ask

How do I set an environment variable in shell?

You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.

How do I set environment variables in Bourne shell?

To set the environment variables system wide in either the Bourne shell or Korn shell, so all users who use Bourne or Korn shell have access to them, add the lines suggested in the subsections to the file /etc/profile . To set them for a specific user only, add them to the file . profile in the user's home directory.

Are environment variables shell specific?

Shell variables are only present in the shell in which they were defined. Environment variables are inherited by child shells but shell variables are not. Shell variable can be made an environment variable by using export command. A script is simply a collection of commands that are intended to run as a group.


2 Answers

You may also use pkgs.stdenv.mkDerivation.shellHook.

let 
  pkgs = import <nixpkgs> {};
  name = "test";
in pkgs.stdenv.mkDerivation {
  buildInputs = [
    pkgs.python
    pkgs.libxml2
  ];
  inherit name;
  shellHook = ''
    export TEST="ABC"
  '';
 }
like image 82
Abdillah Avatar answered Oct 01 '22 23:10

Abdillah


Use buildPythonPackage function (that uses mkDerivation). Passing anything to it will set env variables in bash shell:

with import <nixpkgs> {};

buildPythonPackage {
  name = "test";

  buildInputs = [ pkgs.python pkgs.libxml2 ];

  src = null;

  PGDATA = "...";
}
like image 44
iElectric Avatar answered Oct 02 '22 00:10

iElectric