nix-shell

nix-shell :: { shell } → String → String

A nix-shell invocation with pre-built environment.

Pre-building the environment has the following advantages:

  • Build failures will cancel the effect before it starts.

  • Dependencies will be cached and metadata is available in the dashboard.

  • You don’t have to worry about bringing Nix files into the sandbox.

  • You can reference any variables you have defined in your Nix file.

  • In-effect execution is instant.

Example:

let
  exampleShell = pkgs.mkShell {
    nativeBuildInputs = [ pkgs.hello pkgs.figlet ];
  };
in mkEffect {
  effectScript = ''
    echo 'Hello from plain effect environment'
    ${nix-shell { shell = exampleShell; } ''
      set -euo pipefail
      echo 'Hello from nix-shell environment'
      hello \
        | figlet
    ''}
    echo 'Bye!'
  '';
}

The effects.nix-shell interface is simpler than nix-shell, because it does not need the flags for build and evaluation.

Parameters

run

The bash command to run; nix-shell --run.

Note that this creates a new shell process with default settings. You may want to run

set -euo pipefail

This will make failing statements and missing variables exit the shell. A failing processes feeding into a pipe will cause the whole pipe statement to exit.

shell

The derivation that represents the nix-shell environment to run.

In a flake, this may look like:

nix-shell { shell = self.devShell.${system}; } ""

The shell may be in a separate file. If you don’t mind evaluating packages twice:

nix-shell { shell = import ./shell.nix; } ""

For more efficient evaluation, you can share the Nixpkgs invocation.

Suppose your shell.nix looks like:

let
  config = { };
  pkgs = import ./nixpkgs { inherit config; };
in
  pkgs.mkShell { /* ... */ }

You can change shell.nix to:

let
  config = { };
in
{ pkgs ? import ./nixpkgs { inherit config; } }:
  pkgs.mkShell { /* ... */ }

And reuse pkgs in the invocation:

nix-shell { shell = import ./shell.nix { inherit pkgs; }; } ""

Return value

A string containing a bash statement.

The string context will refer to nix, the built shell dependencies and the shell derivation.

See also