欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Nix Package Manager Guide (2)

程序员文章站 2022-05-31 09:27:50
...

Part VI. Command Reference

This section lists commands and options that you can use when you work with Nix.

Chapter 17. Common Options

Most Nix commands accept the following command-line options:

--help

Prints out a summary of the command syntax and exits.

--version

Prints out the Nix version number on standard output and exits.

--verbose / -v

Increases the level of verbosity of diagnostic messages printed on standard error. For each Nix operation, the information printed on standard output is well-defined; any diagnostic information is printed on standard error, never on standard output.

This option may be specified repeatedly. Currently, the following verbosity levels exist:

0

“Errors only”: only print messages explaining why the Nix invocation failed.

1

“Informational”: print useful messages about what Nix is doing. This is the default.

2

“Talkative”: print more informational messages.

3

“Chatty”: print even more informational messages.

4

“Debug”: print debug information.

5

“Vomit”: print vast amounts of debug information.

--quiet

Decreases the level of verbosity of diagnostic messages printed on standard error. This is the inverse option to -v / --verbose.

This option may be specified repeatedly. See the previous verbosity levels list.

--no-build-output / -Q

By default, output written by builders to standard output and standard error is echoed to the Nix command's standard error. This option suppresses this behaviour. Note that the builder's standard output and error are always written to a log file in prefix/nix/var/log/nix.

--max-jobs / -j number

Sets the maximum number of build jobs that Nix will perform in parallel to the specified number. Specify auto to use the number of CPUs in the system. The default is specified by the max-jobs configuration setting, which itself defaults to 1. A higher value is useful on SMP systems or to exploit I/O latency.

--cores

Sets the value of the NIX_BUILD_CORES environment variable in the invocation of builders. Builders can use this variable at their discretion to control the maximum amount of parallelism. For instance, in Nixpkgs, if the derivation attribute enableParallelBuilding is set to true, the builder passes the -jN flag to GNU Make. It defaults to the value of the coresconfiguration setting, if set, or 1 otherwise. The value 0 means that the builder should use all available CPU cores in the system.

--max-silent-time

Sets the maximum number of seconds that a builder can go without producing any data on standard output or standard error. The default is specified by the max-silent-timeconfiguration setting. 0 means no time-out.

--timeout

Sets the maximum number of seconds that a builder can run. The default is specified by the timeout configuration setting. 0 means no timeout.

--keep-going / -k

Keep going in case of failed builds, to the greatest extent possible. That is, if building an input of some derivation fails, Nix will still build the other inputs, but not the derivation itself. Without this option, Nix stops if any build fails (except for builds of substitutes), possibly killing builds in progress (in case of parallel or distributed builds).

--keep-failed / -K

Specifies that in case of a build failure, the temporary directory (usually in /tmp) in which the build takes place should not be deleted. The path of the build directory is printed as an informational message.

--fallback

Whenever Nix attempts to build a derivation for which substitutes are known for each output path, but realising the output paths through the substitutes fails, fall back on building the derivation.

The most common scenario in which this is useful is when we have registered substitutes in order to perform binary distribution from, say, a network repository. If the repository is down, the realisation of the derivation will fail. When this option is specified, Nix will build the derivation instead. Thus, installation from binaries falls back on installation from source. This option is not the default since it is generally not desirable for a transient failure in obtaining the substitutes to lead to a full build from source (with the related consumption of resources).

--no-build-hook

Disables the build hook mechanism. This allows to ignore remote builders if they are setup on the machine.

It's useful in cases where the bandwidth between the client and the remote builder is too low. In that case it can take more time to upload the sources to the remote builder and fetch back the result than to do the computation locally.

--readonly-mode

When this option is used, no attempt is made to open the Nix database. Most Nix operations do need database access, so those operations will fail.

--arg name value

This option is accepted by nix-envnix-instantiate and nix-build. When evaluating Nix expressions, the expression evaluator will automatically try to call functions that it encounters. It can automatically call functions for which every argument has a default value (e.g., argName ? defaultValue }: ...). With --arg, you can also call functions that have arguments without a default value (or override a default value). That is, if the evaluator encounters a function with an argument named name, it will call it with value value.

For instance, the top-level default.nix in Nixpkgs is actually a function:

{ # The system (e.g., `i686-linux') for which to build the packages.
  system ? builtins.currentSystem
  ...
}: ...

So if you call this Nix expression (e.g., when you do nix-env -i pkgname), the function will be called automatically using the value builtins.currentSystem for the system argument. You can override this using --arg, e.g., nix-env -i pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

--argstr name value

This option is like --arg, only the value is not a Nix expression but a string. So instead of --arg system \"i686-linux\" (the outer quotes are to keep the shell happy) you can say --argstr system i686-linux.

--attr / -A attrPath

Select an attribute from the top-level Nix expression being evaluated. (nix-envnix-instantiatenix-build and nix-shell only.) The attribute path attrPath is a sequence of attribute names separated by dots. For instance, given a top-level Nix expression e, the attribute path xorg.xorgserver would cause the expression e.xorg.xorgserver to be used. See nix-env --install for some concrete examples.

In addition to attribute names, you can also specify array indices. For instance, the attribute path foo.3.bar selects the bar attribute of the fourth element of the array in the foo attribute of the top-level expression.

--expr / -E

Interpret the command line arguments as a list of Nix expressions to be parsed and evaluated, rather than as a list of file names of Nix expressions. (nix-instantiatenix-build and nix-shell only.)

-I path

Add a path to the Nix expression search path. This option may be given multiple times. See the NIX_PATH environment variable for information on the semantics of the Nix search path. Paths added through -I take precedence over NIX_PATH.

--option name value

Set the Nix configuration option name to value. This overrides settings in the Nix configuration file (see nix.conf(5)).

--repair

Fix corrupted or missing store paths by redownloading or rebuilding them. Note that this is slow because it requires computing a cryptographic hash of the contents of every path in the closure of the build. Also note the warning under nix-store --repair-path.

Chapter 18. Common Environment Variables

Most Nix commands interpret the following environment variables:

IN_NIX_SHELL

Indicator that tells if the current environment was set up by nix-shell.

NIX_PATH

A colon-separated list of directories used to look up Nix expressions enclosed in angle brackets (i.e., <path>). For instance, the value

/home/eelco/Dev:/etc/nixos

will cause Nix to look for paths relative to /home/eelco/Dev and /etc/nixos, in that order. It is also possible to match paths against a prefix. For example, the value

nixpkgs=/home/eelco/Dev/nixpkgs-branch:/etc/nixos

will cause Nix to search for <nixpkgs/path> in /home/eelco/Dev/nixpkgs-branch/path and /etc/nixos/nixpkgs/path.

If a path in the Nix search path starts with http:// or https://, it is interpreted as the URL of a tarball that will be downloaded and unpacked to a temporary location. The tarball must consist of a single top-level directory. For example, setting NIX_PATH to

nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-15.09.tar.gz

tells Nix to download the latest revision in the Nixpkgs/NixOS 15.09 channel.

A following shorthand can be used to refer to the official channels:

nixpkgs=channel:nixos-15.09

 

The search path can be extended using the -I option, which takes precedence over NIX_PATH.

NIX_IGNORE_SYMLINK_STORE

Normally, the Nix store directory (typically /nix/store) is not allowed to contain any symlink components. This is to prevent “impure” builds. Builders sometimes “canonicalise” paths by resolving all symlink components. Thus, builds on different machines (with /nix/store resolving to different locations) could yield different results. This is generally not a problem, except when builds are deployed to machines where /nix/store resolves differently. If you are sure that you’re not going to do that, you can set NIX_IGNORE_SYMLINK_STORE to 1.

Note that if you’re symlinking the Nix store so that you can put it on another file system than the root file system, on Linux you’re better off using bind mount points, e.g.,

$ mkdir /nix
$ mount -o bind /mnt/otherdisk/nix /nix

Consult the mount(8) manual page for details.

NIX_STORE_DIR

Overrides the location of the Nix store (default prefix/store).

NIX_DATA_DIR

Overrides the location of the Nix static data directory (default prefix/share).

NIX_LOG_DIR

Overrides the location of the Nix log directory (default prefix/log/nix).

NIX_STATE_DIR

Overrides the location of the Nix state directory (default prefix/var/nix).

NIX_CONF_DIR

Overrides the location of the Nix configuration directory (default prefix/etc/nix).

TMPDIR

Use the specified directory to store temporary files. In particular, this includes temporary build directories; these can take up substantial amounts of disk space. The default is /tmp.

NIX_REMOTE

This variable should be set to daemon if you want to use the Nix daemon to execute Nix operations. This is necessary in multi-user Nix installations. If the Nix daemon's Unix socket is at some non-standard path, this variable should be set to unix://path/to/socket. Otherwise, it should be left unset.

NIX_SHOW_STATS

If set to 1, Nix will print some evaluation statistics, such as the number of values allocated.

NIX_COUNT_CALLS

If set to 1, Nix will print how often functions were called during Nix expression evaluation. This is useful for profiling your Nix expressions.

GC_INITIAL_HEAP_SIZE

If Nix has been configured to use the Boehm garbage collector, this variable sets the initial size of the heap in bytes. It defaults to 384 MiB. Setting it to a low value reduces memory consumption, but will increase runtime due to the overhead of garbage collection.

Chapter 19. Main Commands

This section lists commands and options that you can use when you work with Nix.

Name

nix-env — manipulate or query Nix user environments

Synopsis

nix-env [--help] [--version] [ { --verbose | -v } ...] [ --quiet ] [ --no-build-output | -Q ] [ { --max-jobs | -j } number ] [ --cores number ] [ --max-silent-time number ] [ --timeout number ] [ --keep-going | -k ] [ --keep-failed | -K ] [--fallback] [--readonly-mode] [ -I path ] [ --option name value ]

[--arg name value] [--argstr name value] [ { --file | -f } path ] [ { --profile | -p } path ] [ --system-filter system ] [--dry-runoperation [options...] [arguments...]

Description

The command nix-env is used to manipulate Nix user environments. User environments are sets of software packages available to a user at some point in time. In other words, they are a synthesised view of the programs available in the Nix store. There may be many user environments: different users can have different environments, and individual users can switch between different environments.

nix-env takes exactly one operation flag which indicates the subcommand to be performed. These are documented below.

Selectors

Several commands, such as nix-env -q and nix-env -i, take a list of arguments that specify the packages on which to operate. These are extended regular expressions that must match the entire name of the package. (For details on regular expressions, see regex(7).) The match is case-sensitive. The regular expression can optionally be followed by a dash and a version number; if omitted, any version of the package will match. Here are some examples:

firefox

Matches the package name firefox and any version.

firefox-32.0

Matches the package name firefox and version 32.0.

gtk\\+

Matches the package name gtk+. The + character must be escaped using a backslash to prevent it from being interpreted as a quantifier, and the backslash must be escaped in turn with another backslash to ensure that the shell passes it on.

.\*

Matches any package name. This is the default for most commands.

'.*zip.*'

Matches any package name containing the string zip. Note the dots: '*zip*' does not work, because in a regular expression, the character * is interpreted as a quantifier.

'.*(firefox|chromium).*'

Matches any package name containing the strings firefox or chromium.

 

Common options

This section lists the options that are common to all operations. These options are allowed for every subcommand, though they may not always have an effect. See also Chapter 17, Common Options.

--file / -f path

Specifies the Nix expression (designated below as the active Nix expression) used by the --install--upgrade, and --query --available operations to obtain derivations. The default is ~/.nix-defexpr.

If the argument starts with http:// or https://, it is interpreted as the URL of a tarball that will be downloaded and unpacked to a temporary location. The tarball must include a single top-level directory containing at least a file named default.nix.

--profile / -p path

Specifies the profile to be used by those operations that operate on a profile (designated below as the active profile). A profile is a sequence of user environments called generations, one of which is the current generation.

--dry-run

For the --install--upgrade--uninstall--switch-generation--delete-generations and --rollback operations, this flag will cause nix-env to print what would be done if this flag had not been specified, without actually doing it.

--dry-run also prints out which paths will be substituted (i.e., downloaded) and which paths will be built from source (because no substitute is available).

--system-filter system

By default, operations such as --query --available show derivations matching any platform. This option allows you to use derivations for the specified platform system.

Files

~/.nix-defexpr

A directory that contains the default Nix expressions used by the --install--upgrade, and --query --available operations to obtain derivations. The --file option may be used to override this default.

The Nix expressions in this directory are combined into a single set, with each file as an attribute that has the name of the file. Thus, if ~/.nix-defexpr contains two files, foo and bar, then the default Nix expression will essentially be

{
  foo = import ~/.nix-defexpr/foo;
  bar = import ~/.nix-defexpr/bar;
}

 

The command nix-channel places symlinks to the downloaded Nix expressions from each subscribed channel in this directory.

~/.nix-profile

A symbolic link to the user's current profile. By default, this symlink points to prefix/var/nix/profiles/default. The PATH environment variable should include ~/.nix-profile/binfor the user environment to be visible to the user.

Operation --install

Synopsis

nix-env { --install | -i } [ { --prebuilt-only | -b } ] [ { --attr | -A } ] [--from-expression] [-E] [--from-profile path] [ --preserve-installed | -P ] [ --remove-all | -r ] args...

Description

The install operation creates a new user environment, based on the current generation of the active profile, to which a set of store paths described by args is added. The arguments argsmap to store paths in a number of possible ways:

  • By default, args is a set of derivation names denoting derivations in the active Nix expression. These are realised, and the resulting output paths are installed. Currently installed derivations with a name equal to the name of a derivation being added are removed unless the option --preserve-installed is specified.

    If there are multiple derivations matching a name in args that have the same name (e.g., gcc-3.3.6 and gcc-4.1.1), then the derivation with the highest priority is used. A derivation can define a priority by declaring the meta.priority attribute. This attribute should be a number, with a higher value denoting a lower priority. The default priority is 0.

    If there are multiple matching derivations with the same priority, then the derivation with the highest version will be installed.

    You can force the installation of multiple derivations with the same name by being specific about the versions. For instance, nix-env -i gcc-3.3.6 gcc-4.1.1 will install both version of GCC (and will probably cause a user environment conflict!).

  • If --attr (-A) is specified, the arguments are attribute paths that select attributes from the top-level Nix expression. This is faster than using derivation names and unambiguous. To find out the attribute paths of available packages, use nix-env -qaP.

  • If --from-profile path is given, args is a set of names denoting installed store paths in the profile path. This is an easy way to copy user environment elements from one profile to another.

  • If --from-expression is given, args are Nix functions that are called with the active Nix expression as their single argument. The derivations returned by those function calls are installed. This allows derivations to be specified in an unambiguous way, which is necessary if there are multiple derivations with the same name.

  • If args are store derivations, then these are realised, and the resulting output paths are installed.

  • If args are store paths that are not store derivations, then these are realised and installed.

  • By default all outputs are installed for each derivation. That can be reduced by setting meta.outputsToInstall.

 

Flags

--prebuilt-only / -b

Use only derivations for which a substitute is registered, i.e., there is a pre-built binary available that can be downloaded in lieu of building the derivation. Thus, no packages will be built from source.

--preserve-installed-P

Do not remove derivations with a name matching one of the derivations being installed. Usually, trying to have two versions of the same package installed in the same generation of a profile will lead to an error in building the generation, due to file name *es between the two versions. However, this is not the case for all packages.

--remove-all-r

Remove all previously installed packages first. This is equivalent to running nix-env -e '.*' first, except that everything happens in a single transaction.

Examples

To install a specific version of gcc from the active Nix expression:

$ nix-env --install gcc-3.3.2
installing `gcc-3.3.2'
uninstalling `gcc-3.1'

Note the previously installed version is removed, since --preserve-installed was not specified.

To install an arbitrary version:

$ nix-env --install gcc
installing `gcc-3.3.2'

 

To install using a specific attribute:

$ nix-env -i -A gcc40mips
$ nix-env -i -A xorg.xorgserver

 

To install all derivations in the Nix expression foo.nix:

$ nix-env -f ~/foo.nix -i '.*'

 

To copy the store path with symbolic name gcc from another profile:

$ nix-env -i --from-profile /nix/var/nix/profiles/foo gcc

 

To install a specific store derivation (typically created by nix-instantiate):

$ nix-env -i /nix/store/fibjb1bfbpm5mrsxc4mh2d8n37sxh91i-gcc-3.4.3.drv

 

To install a specific output path:

$ nix-env -i /nix/store/y3cgx0xj1p4iv9x0pnnmdhr8iyg741vk-gcc-3.4.3

 

To install from a Nix expression specified on the command-line:

$ nix-env -f ./foo.nix -i -E \
    'f: (f {system = "i686-linux";}).subversionWithJava'

I.e., this evaluates to (f: (f {system = "i686-linux";}).subversionWithJava) (import ./foo.nix), thus selecting the subversionWithJava attribute from the set returned by calling the function defined in ./foo.nix.

A dry-run tells you which paths will be downloaded or built from source:

$ nix-env -f '<nixpkgs>' -iA hello --dry-run
(dry run; not doing anything)
installing ‘hello-2.10’
these paths will be fetched (0.04 MiB download, 0.19 MiB unpacked):
  /nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10
  ...

 

To install Firefox from the latest revision in the Nixpkgs/NixOS 14.12 channel:

$ nix-env -f https://github.com/NixOS/nixpkgs-channels/archive/nixos-14.12.tar.gz -iA firefox

(The GitHub repository nixpkgs-channels is updated automatically from the main nixpkgs repository after certain tests have succeeded and binaries have been built and uploaded to the binary cache at cache.nixos.org.)

Operation --upgrade

Synopsis

nix-env { --upgrade | -u } [ { --prebuilt-only | -b } ] [ { --attr | -A } ] [--from-expression] [-E] [--from-profile path] [ --lt | --leq | --eq | --always ] args...

Description

The upgrade operation creates a new user environment, based on the current generation of the active profile, in which all store paths are replaced for which there are newer versions in the set of paths described by args. Paths for which there are no newer versions are left untouched; this is not an error. It is also not an error if an element of args matches no installed derivations.

For a description of how args is mapped to a set of store paths, see --install. If args describes multiple store paths with the same symbolic name, only the one with the highest version is installed.

Flags

--lt

Only upgrade a derivation to newer versions. This is the default.

--leq

In addition to upgrading to newer versions, also “upgrade” to derivations that have the same version. Version are not a unique identification of a derivation, so there may be many derivations that have the same version. This flag may be useful to force “synchronisation” between the installed and available derivations.

--eq

Only “upgrade” to derivations that have the same version. This may not seem very useful, but it actually is, e.g., when there is a new release of Nixpkgs and you want to replace installed applications with the same versions built against newer dependencies (to reduce the number of dependencies floating around on your system).

--always

In addition to upgrading to newer versions, also “upgrade” to derivations that have the same or a lower version. I.e., derivations may actually be downgraded depending on what is available in the active Nix expression.

For the other flags, see --install.

Examples

$ nix-env --upgrade gcc
upgrading `gcc-3.3.1' to `gcc-3.4'

$ nix-env -u gcc-3.3.2 --always (switch to a specific version)
upgrading `gcc-3.4' to `gcc-3.3.2'

$ nix-env --upgrade pan
(no upgrades available, so nothing happens)

$ nix-env -u (try to upgrade everything)
upgrading `hello-2.1.2' to `hello-2.1.3'
upgrading `mozilla-1.2' to `mozilla-1.4'

Versions

The upgrade operation determines whether a derivation y is an upgrade of a derivation x by looking at their respective name attributes. The names (e.g., gcc-3.3.1 are split into two parts: the package name (gcc), and the version (3.3.1). The version part starts after the first dash not following by a letter. x is considered an upgrade of y if their package names match, and the version of y is higher that that of x.

The versions are compared by splitting them into contiguous components of numbers and letters. E.g., 3.3.1pre5 is split into [3, 3, 1, "pre", 5]. These lists are then compared lexicographically (from left to right). Corresponding components a and b are compared as follows. If they are both numbers, integer comparison is used. If a is an empty string and b is a number, a is considered less than b. The special string component pre (for pre-release) is considered to be less than other components. String components are considered less than number components. Otherwise, they are compared lexicographically (i.e., using case-sensitive string comparison).

This is illustrated by the following examples:

1.0 < 2.3
2.1 < 2.3
2.3 = 2.3
2.5 > 2.3
3.1 > 2.3
2.3.1 > 2.3
2.3.1 > 2.3a
2.3pre1 < 2.3
2.3pre3 < 2.3pre12
2.3a < 2.3c
2.3pre1 < 2.3c
2.3pre1 < 2.3q

 

Operation --uninstall

Synopsis

nix-env { --uninstall | -e } drvnames...

Description

The uninstall operation creates a new user environment, based on the current generation of the active profile, from which the store paths designated by the symbolic names names are removed.

Examples

$ nix-env --uninstall gcc
$ nix-env -e '.*' (remove everything)

Operation --set

Synopsis

nix-env --set drvname

Description

The --set operation modifies the current generation of a profile so that it contains exactly the specified derivation, and nothing else.

Examples

The following updates a profile such that its current generation will contain just Firefox:

$ nix-env -p /nix/var/nix/profiles/browser --set firefox

 

Operation --set-flag

Synopsis

nix-env --set-flag name value drvnames...

Description

The --set-flag operation allows meta attributes of installed packages to be modified. There are several attributes that can be usefully modified, because they affect the behaviour of nix-env or the user environment build script:

  • priority can be changed to resolve filename *es. The user environment build script uses the meta.priority attribute of derivations to resolve filename collisions between packages. Lower priority values denote a higher priority. For instance, the GCC wrapper package and the Binutils package in Nixpkgs both have a file bin/ld, so previously if you tried to install both you would get a collision. Now, on the other hand, the GCC wrapper declares a higher priority than Binutils, so the former’s bin/ld is symlinked in the user environment.

  • keep can be set to true to prevent the package from being upgraded or replaced. This is useful if you want to hang on to an older version of a package.

  • active can be set to false to “disable” the package. That is, no symlinks will be generated to the files of the package, but it remains part of the profile (so it won’t be garbage-collected). It can be set back to true to re-enable the package.

 

Examples

To prevent the currently installed Firefox from being upgraded:

$ nix-env --set-flag keep true firefox

After this, nix-env -u will ignore Firefox.

To disable the currently installed Firefox, then install a new Firefox while the old remains part of the profile:

$ nix-env -q
firefox-2.0.0.9 (the current one)

$ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11'
building path(s) `/nix/store/myy0y59q3ig70dgq37jqwg1j0rsapzsl-user-environment'
collision between `/nix/store/...-firefox-2.0.0.11/bin/firefox'
  and `/nix/store/...-firefox-2.0.0.9/bin/firefox'.
(i.e., can’t have two active at the same time)

$ nix-env --set-flag active false firefox
setting flag on `firefox-2.0.0.9'

$ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11'

$ nix-env -q
firefox-2.0.0.11 (the enabled one)
firefox-2.0.0.9 (the disabled one)

 

To make files from binutils take precedence over files from gcc:

$ nix-env --set-flag priority 5 binutils
$ nix-env --set-flag priority 10 gcc

 

Operation --query

Synopsis

nix-env { --query | -q } [ --installed | --available | -a ]

[ { --status | -s } ] [ { --attr-path | -P } ] [--no-name] [ { --compare-versions | -c } ] [--system] [--drv-path] [--out-path] [--description] [--meta]

[--xml] [--json] [ { --prebuilt-only | -b } ] [ { --attr | -A } attribute-path ]

names...

Description

The query operation displays information about either the store paths that are installed in the current generation of the active profile (--installed), or the derivations that are available for installation in the active Nix expression (--available). It only prints information about derivations whose symbolic name matches one of names.

The derivations are sorted by their name attributes.

Source selection

The following flags specify the set of things on which the query operates.

--installed

The query operates on the store paths that are installed in the current generation of the active profile. This is the default.

--available-a

The query operates on the derivations that are available in the active Nix expression.

Queries

The following flags specify what information to display about the selected derivations. Multiple flags may be specified, in which case the information is shown in the order given here. Note that the name of the derivation is shown unless --no-name is specified.

--xml

Print the result in an XML representation suitable for automatic processing by other tools. The root element is called items, which contains a item element for each available or installed derivation. The fields discussed below are all stored in attributes of the item elements.

--json

Print the result in a JSON representation suitable for automatic processing by other tools.

--prebuilt-only / -b

Show only derivations for which a substitute is registered, i.e., there is a pre-built binary available that can be downloaded in lieu of building the derivation. Thus, this shows all packages that probably can be installed quickly.

--status-s

Print the status of the derivation. The status consists of three characters. The first is I or -, indicating whether the derivation is currently installed in the current generation of the active profile. This is by definition the case for --installed, but not for --available. The second is P or -, indicating whether the derivation is present on the system. This indicates whether installation of an available derivation will require the derivation to be built. The third is S or -, indicating whether a substitute is available for the derivation.

--attr-path-P

Print the attribute path of the derivation, which can be used to unambiguously select it using the --attr option available in commands that install derivations like nix-env --install.

--no-name

Suppress printing of the name attribute of each derivation.

--compare-versions / -c

Compare installed versions to available versions, or vice versa (if --available is given). This is useful for quickly seeing whether upgrades for installed packages are available in a Nix expression. A column is added with the following meaning:

< version

A newer version of the package is available or installed.

= version

At most the same version of the package is available or installed.

> version

Only older versions of the package are available or installed.

- ?

No version of the package is available or installed.

 

--system

Print the system attribute of the derivation.

--drv-path

Print the path of the store derivation.

--out-path

Print the output path of the derivation.

--description

Print a short (one-line) description of the derivation, if available. The description is taken from the meta.description attribute of the derivation.

--meta

Print all of the meta-attributes of the derivation. This option is only available with --xml or --json.

Examples

To show installed packages:

$ nix-env -q
bison-1.875c
docbook-xml-4.2
firefox-1.0.4
MPlayer-1.0pre7
ORBit2-2.8.3

 

To show available packages:

$ nix-env -qa
firefox-1.0.7
GConf-2.4.0.1
MPlayer-1.0pre7
ORBit2-2.8.3

 

To show the status of available packages:

$ nix-env -qas
-P- firefox-1.0.7   (not installed but present)
--S GConf-2.4.0.1   (not present, but there is a substitute for fast installation)
--S MPlayer-1.0pre3 (i.e., this is not the installed MPlayer, even though the version is the same!)
IP- ORBit2-2.8.3    (installed and by definition present)

 

To show available packages in the Nix expression foo.nix:

$ nix-env -f ./foo.nix -qa
foo-1.2.3

 

To compare installed versions to what’s available:

$ nix-env -qc
...
acrobat-reader-7.0 - ?      (package is not available at all)
autoconf-2.59      = 2.59   (same version)
firefox-1.0.4      < 1.0.7  (a more recent version is available)
...

 

To show all packages with “zip” in the name:

$ nix-env -qa '.*zip.*'
bzip2-1.0.6
gzip-1.6
zip-3.0

 

To show all packages with “firefox” or “chromium” in the name:

$ nix-env -qa '.*(firefox|chromium).*'
chromium-37.0.2062.94
chromium-beta-38.0.2125.24
firefox-32.0.3
firefox-with-plugins-13.0.1

 

To show all packages in the latest revision of the Nixpkgs repository:

$ nix-env -f https://github.com/NixOS/nixpkgs/archive/master.tar.gz -qa

 

Operation --switch-profile

Synopsis

nix-env { --switch-profile | -S } {path}

Description

This operation makes path the current profile for the user. That is, the symlink ~/.nix-profile is made to point to path.

Examples

$ nix-env -S ~/my-profile

Operation --list-generations

Synopsis

nix-env --list-generations

Description

This operation print a list of all the currently existing generations for the active profile. These may be switched to using the --switch-generation operation. It also prints the creation date of the generation, and indicates the current generation.

Examples

$ nix-env --list-generations
  95   2004-02-06 11:48:24
  96   2004-02-06 11:49:01
  97   2004-02-06 16:22:45
  98   2004-02-06 16:24:33   (current)

Operation --delete-generations

Synopsis

nix-env --delete-generations generations...

Description

This operation deletes the specified generations of the current profile. The generations can be a list of generation numbers, the special value old to delete all non-current generations, a value such as 30d to delete all generations older than the specified number of days (except for the generation that was active at that point in time), or a value such as. +5 to only keep the specified items older than the current generation. Periodically deleting old generations is important to make garbage collection effective.

Examples

$ nix-env --delete-generations 3 4 8

$ nix-env --delete-generations +5

$ nix-env --delete-generations 30d

$ nix-env -p other_profile --delete-generations old

Operation --switch-generation

Synopsis

nix-env { --switch-generation | -G } {generation}

Description

This operation makes generation number generation the current generation of the active profile. That is, if the profile is the path to the active profile, then the symlink profile is made to point to profile-generation-link, which is in turn a symlink to the actual user environment in the Nix store.

Switching will fail if the specified generation does not exist.

Examples

$ nix-env -G 42
switching from generation 50 to 42

Operation --rollback

Synopsis

nix-env --rollback

Description

This operation switches to the “previous” generation of the active profile, that is, the highest numbered generation lower than the current generation, if it exists. It is just a convenience wrapper around --list-generations and --switch-generation.

Examples

$ nix-env --rollback
switching from generation 92 to 91

$ nix-env --rollback
error: no generation older than the current (91) exists

Name

nix-build — build a Nix expression

Synopsis

nix-build [--help] [--version] [ { --verbose | -v } ...] [ --quiet ] [ --no-build-output | -Q ] [ { --max-jobs | -j } number ] [ --cores number ] [ --max-silent-time number ] [ --timeout number ] [ --keep-going | -k ] [ --keep-failed | -K ] [--fallback] [--readonly-mode] [ -I path ] [ --option name value ]

[--arg name value] [--argstr name value] [ { --attr | -A } attrPath ] [--no-out-link] [ { --out-link | -o } outlink ] paths...

Description

The nix-build command builds the derivations described by the Nix expressions in paths. If the build succeeds, it places a symlink to the result in the current directory. The symlink is called result. If there are multiple Nix expressions, or the Nix expressions evaluate to multiple derivations, multiple sequentially numbered symlinks are created (resultresult-2, and so on).

If no paths are specified, then nix-build will use default.nix in the current directory, if it exists.

If an element of paths starts with http:// or https://, it is interpreted as the URL of a tarball that will be downloaded and unpacked to a temporary location. The tarball must include a single top-level directory containing at least a file named default.nix.

nix-build is essentially a wrapper around nix-instantiate (to translate a high-level Nix expression to a low-level store derivation) and nix-store --realise (to build the store derivation).

Warning: The result of the build is automatically registered as a root of the Nix garbage collector. This root disappears automatically when the result symlink is deleted or renamed. So don’t rename the symlink.

Options

All options not listed here are passed to nix-store --realise, except for --arg and --attr / -A which are passed to nix-instantiate. See also Chapter 17, Common Options.

--no-out-link

Do not create a symlink to the output path. Note that as a result the output does not become a root of the garbage collector, and so might be deleted by nix-store --gc.

--out-link / -o outlink

Change the name of the symlink to the output path created from result to outlink.

The following common options are supported:

Examples

$ nix-build '<nixpkgs>' -A firefox
store derivation is /nix/store/qybprl8sz2lc...-firefox-1.5.0.7.drv
/nix/store/d18hyl92g30l...-firefox-1.5.0.7

$ ls -l result
lrwxrwxrwx  ...  result -> /nix/store/d18hyl92g30l...-firefox-1.5.0.7

$ ls ./result/bin/
firefox  firefox-config

If a derivation has multiple outputs, nix-build will build the default (first) output. You can also build all outputs:

$ nix-build '<nixpkgs>' -A openssl.all

This will create a symlink for each output named result-outputname. The suffix is omitted if the output name is out. So if openssl has outputs outbin and mannix-build will create symlinks resultresult-bin and result-man. It’s also possible to build a specific output:

$ nix-build '<nixpkgs>' -A openssl.man

This will create a symlink result-man.

Build a Nix expression given on the command line:

$ nix-build -E 'with import <nixpkgs> { }; runCommand "foo" { } "echo bar > $out"'
$ cat ./result
bar

 

Build the GNU Hello package from the latest revision of the master branch of Nixpkgs:

$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello

 


Name

nix-shell — start an interactive shell based on a Nix expression

Synopsis

nix-shell [--arg name value] [--argstr name value] [ { --attr | -A } attrPath ] [--command cmd] [--run cmd] [--exclude regexp] [--pure] [--keep name] { { --packages | -p }packages... | [path]}

Description

The command nix-shell will build the dependencies of the specified derivation, but not the derivation itself. It will then start an interactive shell in which all environment variables defined by the derivation path have been set to their corresponding values, and the script $stdenv/setup has been sourced. This is useful for reproducing the environment of a derivation for development.

If path is not given, nix-shell defaults to shell.nix if it exists, and default.nix otherwise.

If path starts with http:// or https://, it is interpreted as the URL of a tarball that will be downloaded and unpacked to a temporary location. The tarball must include a single top-level directory containing at least a file named default.nix.

If the derivation defines the variable shellHook, it will be evaluated after $stdenv/setup has been sourced. Since this hook is not executed by regular Nix builds, it allows you to perform initialisation specific to nix-shell. For example, the derivation attribute

shellHook =
  ''
    echo "Hello shell"
  '';

will cause nix-shell to print Hello shell.

Options

All options not listed here are passed to nix-store --realise, except for --arg and --attr / -A which are passed to nix-instantiate. See also Chapter 17, Common Options.

--command cmd

In the environment of the derivation, run the shell command cmd. This command is executed in an interactive shell. (Use --run to use a non-interactive shell instead.) However, a call toexit is implicitly added to the command, so the shell will exit after running the command. To prevent this, add return at the end; e.g. --command "echo Hello; return" will print Helloand then drop you into the interactive shell. This can be useful for doing any additional initialisation.

--run cmd

Like --command, but executes the command in a non-interactive shell. This means (among other things) that if you hit Ctrl-C while the command is running, the shell exits.

--exclude regexp

Do not build any dependencies whose store path matches the regular expression regexp. This option may be specified multiple times.

--pure

If this flag is specified, the environment is almost entirely cleared before the interactive shell is started, so you get an environment that more closely corresponds to the “real” Nix build. A few variables, in particular HOMEUSER and DISPLAY, are retained. Note that ~/.bashrc and (depending on your Bash installation) /etc/bashrc are still sourced, so any variables set there will affect the interactive shell.

--packages / -p packages

Set up an environment in which the specified packages are present. The command line arguments are interpreted as attribute names inside the Nix Packages collection. Thus, nix-shell -p libjpeg openjdk will start a shell in which the packages denoted by the attribute names libjpeg and openjdk are present.

-i interpreter

The chained script interpreter to be invoked by nix-shell. Only applicable in #!-scripts (described below).

--keep name

When a --pure shell is started, keep the listed environment variables.

The following common options are supported:

Environment variables

NIX_BUILD_SHELL

Shell used to start the interactive environment. Defaults to the bash found in PATH.

Examples

To build the dependencies of the package Pan, and start an interactive shell in which to build it:

$ nix-shell '<nixpkgs>' -A pan
[nix-shell]$ unpackPhase
[nix-shell]$ cd pan-*
[nix-shell]$ configurePhase
[nix-shell]$ buildPhase
[nix-shell]$ ./pan/gui/pan

To clear the environment first, and do some additional automatic initialisation of the interactive shell:

$ nix-shell '<nixpkgs>' -A pan --pure \
    --command 'export NIX_DEBUG=1; export NIX_CORES=8; return'

Nix expressions can also be given on the command line. For instance, the following starts a shell containing the packages sqlite and libX11:

$ nix-shell -E 'with import <nixpkgs> { }; runCommand "dummy" { buildInputs = [ sqlite xorg.libX11 ]; } ""'

A shorter way to do the same is:

$ nix-shell -p sqlite xorg.libX11
[nix-shell]$ echo $NIX_LDFLAGS
… -L/nix/store/j1zg5v…-sqlite-3.8.0.2/lib -L/nix/store/0gmcz9…-libX11-1.6.1/lib …

The -p flag looks up Nixpkgs in the Nix search path. You can override it by passing -I or setting NIX_PATH. For example, the following gives you a shell containing the Pan package from a specific revision of Nixpkgs:

$ nix-shell -p pan -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/8a3eea054838b55aca962c3fbde9c83c102b8bf2.tar.gz

[nix-shell:~]$ pan --version
Pan 0.139

 

Use as a #!-interpreter

You can use nix-shell as a script interpreter to allow scripts written in arbitrary languages to obtain their own dependencies via Nix. This is done by starting the script with the following lines:

#! /usr/bin/env nix-shell
#! nix-shell -i real-interpreter -p packages

where real-interpreter is the “real” script interpreter that will be invoked by nix-shell after it has obtained the dependencies and initialised the environment, and packages are the attribute names of the dependencies in Nixpkgs.

The lines starting with #! nix-shell specify nix-shell options (see above). Note that you cannot write #! /usr/bin/env nix-shell -i ... because many operating systems only allow one argument in #! lines.

For example, here is a Python script that depends on Python and the prettytable package:

#! /usr/bin/env nix-shell
#! nix-shell -i python -p python pythonPackages.prettytable

import prettytable

# Print a simple table.
t = prettytable.PrettyTable(["N", "N^2"])
for n in range(1, 10): t.add_row([n, n * n])
print t

 

Similarly, the following is a Perl script that specifies that it requires Perl and the HTML::TokeParser::Simple and LWP packages:

#! /usr/bin/env nix-shell
#! nix-shell -i perl -p perl perlPackages.HTMLTokeParserSimple perlPackages.LWP

use HTML::TokeParser::Simple;

# Fetch nixos.org and print all hrefs.
my $p = HTML::TokeParser::Simple->new(url => 'http://nixos.org/');

while (my $token = $p->get_tag("a")) {
    my $href = $token->get_attr("href");
    print "$href\n" if $href;
}

 

Sometimes you need to pass a simple Nix expression to customize a package like Terraform:

#! /usr/bin/env nix-shell
#! nix-shell -i bash -p "terraform.withPlugins (plugins: [ plugins.openstack ])"

terraform apply

 

Note: You must use double quotes (") when passing a simple Nix expression in a nix-shell shebang.

 

Finally, using the merging of multiple nix-shell shebangs the following Haskell script uses a specific branch of Nixpkgs/NixOS (the 18.03 stable branch):

#! /usr/bin/env nix-shell
#! nix-shell -i runghc -p haskellPackages.ghc haskellPackages.HTTP haskellPackages.tagsoup
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-18.03.tar.gz

import Network.HTTP
import Text.HTML.TagSoup

-- Fetch nixos.org and print all hrefs.
main = do
  resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/")
  body <- getResponseBody resp
  let tags = filter (isTagOpenName "a") $ parseTags body
  let tags' = map (fromAttrib "href") tags
  mapM_ putStrLn $ filter (/= "") tags'

If you want to be even more precise, you can specify a specific revision of Nixpkgs:

#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/0672315759b3e15e2121365f067c1c8c56bb4722.tar.gz

 

The examples above all used -p to get dependencies from Nixpkgs. You can also use a Nix expression to build your own dependencies. For example, the Python example could have been written as:

#! /usr/bin/env nix-shell
#! nix-shell deps.nix -i python

where the file deps.nix in the same directory as the #!-script contains:

with import <nixpkgs> {};

runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } ""

 


Name

nix-store — manipulate or query the Nix store

Synopsis

nix-store [--help] [--version] [ { --verbose | -v } ...] [ --quiet ] [ --no-build-output | -Q ] [ { --max-jobs | -j } number ] [ --cores number ] [ --max-silent-time number ] [ --timeout number ] [ --keep-going | -k ] [ --keep-failed | -K ] [--fallback] [--readonly-mode] [ -I path ] [ --option name value ]

[--add-root path] [--indirectoperation [options...] [arguments...]

Description

The command nix-store performs primitive operations on the Nix store. You generally do not need to run this command manually.

nix-store takes exactly one operation flag which indicates the subcommand to be performed. These are documented below.

Common options

This section lists the options that are common to all operations. These options are allowed for every subcommand, though they may not always have an effect. See also Chapter 17, Common Options for a list of common options.

--add-root path

Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector (see Section 11.1, “Garbage Collector Roots”). The root is stored in path, which must be inside a directory that is scanned for roots by the garbage collector (i.e., typically in a subdirectory of /nix/var/nix/gcroots/unless the --indirect flag is used.

If there are multiple results, then multiple symlinks will be created by sequentially numbering symlinks beyond the first one (e.g., foofoo-2foo-3, and so on).

--indirect

In conjunction with --add-root, this option allows roots to be stored outside of the GC roots directory. This is useful for commands such as nix-build that place a symlink to the build result in the current directory; such a build result should not be garbage-collected unless the symlink is removed.

The --indirect flag causes a uniquely named symlink to path to be stored in /nix/var/nix/gcroots/auto/. For instance,

$ nix-store --add-root /home/eelco/bla/result --indirect -r ...

$ ls -l /nix/var/nix/gcroots/auto
lrwxrwxrwx    1 ... 2005-03-13 21:10 dn54lcypm8f8... -> /home/eelco/bla/result

$ ls -l /home/eelco/bla/result
lrwxrwxrwx    1 ... 2005-03-13 21:10 /home/eelco/bla/result -> /nix/store/1r11343n6qd4...-f-spot-0.0.10

Thus, when /home/eelco/bla/result is removed, the GC root in the auto directory becomes a dangling symlink and will be ignored by the collector.

Warning: Note that it is not possible to move or rename indirect GC roots, since the symlink in the auto directory will still point to the old location.

Operation --realise

Synopsis

nix-store { --realise | -r } paths... [--dry-run]

Description

The operation --realise essentially “builds” the specified store paths. Realisation is a somewhat overloaded term:

  • If the store path is a derivation, realisation ensures that the output paths of the derivation are valid (i.e., the output path and its closure exist in the file system). This can be done in several ways. First, it is possible that the outputs are already valid, in which case we are done immediately. Otherwise, there may be substitutes that produce the outputs (e.g., by downloading them). Finally, the outputs can be produced by performing the build action described by the derivation.

  • If the store path is not a derivation, realisation ensures that the specified path is valid (i.e., it and its closure exist in the file system). If the path is already valid, we are done immediately. Otherwise, the path and any missing paths in its closure may be produced through substitutes. If there are no (successful) subsitutes, realisation fails.

 

The output path of each derivation is printed on standard output. (For non-derivations argument, the argument itself is printed.)

The following flags are available:

--dry-run

Print on standard error a description of what packages would be built or downloaded, without actually performing the operation.

--ignore-unknown

If a non-derivation path does not have a substitute, then silently ignore it.

--check

This option allows you to check whether a derivation is deterministic. It rebuilds the specified derivation and checks whether the result is bitwise-identical with the existing outputs, printing an error if that’s not the case. The outputs of the specified derivation must already exist. When used with -K, if an output path is not identical to the corresponding output from the previous build, the new output path is left in /nix/store/name.check.

See also the build-repeat configuration option, which repeats a derivation a number of times and prevents its outputs from being registered as “valid” in the Nix store unless they are identical.

Examples

This operation is typically used to build store derivations produced by nix-instantiate:

$ nix-store -r $(nix-instantiate ./test.nix)
/nix/store/31axcgrlbfsxzmfff1gyj1bf62hvkby2-aterm-2.3.1

This is essentially what nix-build does.

To test whether a previously-built derivation is deterministic:

$ nix-build '<nixpkgs>' -A hello --check -K

 

Operation --serve

Synopsis

nix-store --serve [--write]

Description

The operation --serve provides access to the Nix store over stdin and stdout, and is intended to be used as a means of providing Nix store access to a restricted ssh user.

The following flags are available:

--write

Allow the connected client to request the realization of derivations. In effect, this can be used to make the host act as a remote builder.

Examples

To turn a host into a build server, the authorized_keys file can be used to provide build access to a given SSH public key:

$ cat <<EOF >>/root/.ssh/authorized_keys
command="nice -n20 nix-store --serve --write" ssh-rsa AAAAB3NzaC1yc2EAAAA...
EOF

 

Operation --gc

Synopsis

nix-store --gc [ --print-roots | --print-live | --print-dead | --delete ] [--max-freed bytes]

Description

Without additional flags, the operation --gc performs a garbage collection on the Nix store. That is, all paths in the Nix store not reachable via file system references from a set of “roots”, are deleted.

The following suboperations may be specified:

--print-roots

This operation prints on standard output the set of roots used by the garbage collector. What constitutes a root is described in Section 11.1, “Garbage Collector Roots”.

--print-live

This operation prints on standard output the set of “live” store paths, which are all the store paths reachable from the roots. Live paths should never be deleted, since that would break consistency — it would become possible that applications are installed that reference things that are no longer present in the store.

--print-dead

This operation prints out on standard output the set of “dead” store paths, which is just the opposite of the set of live paths: any path in the store that is not live (with respect to the roots) is dead.

--delete

This operation performs an actual garbage collection. All dead paths are removed from the store. This is the default.

By default, all unreachable paths are deleted. The following options control what gets deleted and in what order:

--max-freed bytes

Keep deleting paths until at least bytes bytes have been deleted, then stop. The argument bytes can be followed by the multiplicative suffix KMG or T, denoting KiB, MiB, GiB or TiB units.

 

The behaviour of the collector is also influenced by the keep-outputs and keep-derivations variables in the Nix configuration file.

With --delete, the collector prints the total number of freed bytes when it finishes (or when it is interrupted). With --print-dead, it prints the number of bytes that would be freed.

Examples

To delete all unreachable paths, just do:

$ nix-store --gc
deleting `/nix/store/kq82idx6g0nyzsp2s14gfsc38npai7lf-cairo-1.0.4.tar.gz.drv'
...
8825586 bytes freed (8.42 MiB)

 

To delete at least 100 MiBs of unreachable paths:

$ nix-store --gc --max-freed $((100 * 1024 * 1024))

 

Operation --delete

Synopsis

nix-store --delete [--ignore-livenesspaths...

Description

The operation --delete deletes the store paths paths from the Nix store, but only if it is safe to do so; that is, when the path is not reachable from a root of the garbage collector. This means that you can only delete paths that would also be deleted by nix-store --gc. Thus, --delete is a more targeted version of --gc.

With the option --ignore-liveness, reachability from the roots is ignored. However, the path still won’t be deleted if there are other paths in the store that refer to it (i.e., depend on it).

Example

$ nix-store --delete /nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4
0 bytes freed (0.00 MiB)
error: cannot delete path `/nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4' since it is still alive

Operation --query

Synopsis

nix-store { --query | -q } { --outputs | --requisites | -R | --references | --referrers | --referrers-closure | --deriver | -d | --graph | --tree | --binding name | -b name | --hash | --size | --roots } [--use-output] [-u] [--force-realise] [-fpaths...

Description

The operation --query displays various bits of information about the store paths . The queries are described below. At most one query can be specified. The default query is --outputs.

The paths paths may also be symlinks from outside of the Nix store, to the Nix store. In that case, the query is applied to the target of the symlink.

Common query options

--use-output-u

For each argument to the query that is a store derivation, apply the query to the output path of the derivation instead.

--force-realise-f

Realise each argument to the query first (see nix-store --realise).

Queries

--outputs

Prints out the output paths of the store derivations paths. These are the paths that will be produced when the derivation is built.

--requisites-R

Prints out the closure of the store path paths.

This query has one option:

--include-outputs

Also include the output path of store derivations, and their closures.

This query can be used to implement various kinds of deployment. A source deployment is obtained by distributing the closure of a store derivation. A binary deployment is obtained by distributing the closure of an output path. A cache deployment (combined source/binary deployment, including binaries of build-time-only dependencies) is obtained by distributing the closure of a store derivation and specifying the option --include-outputs.

--references

Prints the set of references of the store paths paths, that is, their immediate dependencies. (For all dependencies, use --requisites.)

--referrers

Prints the set of referrers of the store paths paths, that is, the store paths currently existing in the Nix store that refer to one of paths. Note that contrary to the references, the set of referrers is not constant; it can change as store paths are added or removed.

--referrers-closure

Prints the closure of the set of store paths paths under the referrers relation; that is, all store paths that directly or indirectly refer to one of paths. These are all the path currently in the Nix store that are dependent on paths.

--deriver-d

Prints the deriver of the store paths paths. If the path has no deriver (e.g., if it is a source file), or if the deriver is not known (e.g., in the case of a binary-only deployment), the stringunknown-deriver is printed.

--graph

Prints the references graph of the store paths paths in the format of the dot tool of AT&T's Graphviz package. This can be used to visualise dependency graphs. To obtain a build-time dependency graph, apply this to a store derivation. To obtain a runtime dependency graph, apply it to an output path.

--tree

Prints the references graph of the store paths paths as a nested ASCII tree. References are ordered by descending closure size; this tends to flatten the tree, making it more readable. The query only recurses into a store path when it is first encountered; this prevents a blowup of the tree representation of the graph.

--graphml

Prints the references graph of the store paths paths in the GraphML file format. This can be used to visualise dependency graphs. To obtain a build-time dependency graph, apply this to a store derivation. To obtain a runtime dependency graph, apply it to an output path.

--binding name-b name

Prints the value of the attribute name (i.e., environment variable) of the store derivations paths. It is an error for a derivation to not have the specified attribute.

--hash

Prints the SHA-256 hash of the contents of the store paths paths (that is, the hash of the output of nix-store --dump on the given paths). Since the hash is stored in the Nix database, this is a fast operation.

--size

Prints the size in bytes of the contents of the store paths paths — to be precise, the size of the output of nix-store --dump on the given paths. Note that the actual disk space required by the store paths may be higher, especially on filesystems with large cluster sizes.

--roots

Prints the garbage collector roots that point, directly or indirectly, at the store paths paths.

Examples

Print the closure (runtime dependencies) of the svn program in the current user environment:

$ nix-store -qR $(which svn)
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/nix/store/9lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4
...

 

Print the build-time dependencies of svn:

$ nix-store -qR $(nix-store -qd $(which svn))
/nix/store/02iizgn86m42q905rddvg4ja975bk2i4-grep-2.5.1.tar.bz2.drv
/nix/store/07a2bzxmzwz5hp58nf03pahrv2ygwgs3-gcc-wrapper.sh
/nix/store/0ma7c9wsbaxahwwl04gbw3fcd806ski4-glibc-2.3.4.drv
... lots of other paths ...

The difference with the previous example is that we ask the closure of the derivation (-qd), not the closure of the output path that contains svn.

Show the build-time dependencies as a tree:

$ nix-store -q --tree $(nix-store -qd $(which svn))
/nix/store/7i5082kfb6yjbqdbiwdhhza0am2xvh6c-subversion-1.1.4.drv
+---/nix/store/d8afh10z72n8l1cr5w42366abiblgn54-builder.sh
+---/nix/store/fmzxmpjx2lh849ph0l36snfj9zdibw67-bash-3.0.drv
|   +---/nix/store/570hmhmx3v57605cqg9yfvvyh0nnb8k8-bash
|   +---/nix/store/p3srsbd8dx44v2pg6nbnszab5mcwx03v-builder.sh
...

 

Show all paths that depend on the same OpenSSL library as svn:

$ nix-store -q --referrers $(nix-store -q --binding openssl $(nix-store -qd $(which svn)))
/nix/store/23ny9l9wixx21632y2wi4p585qhva1q8-sylpheed-1.0.0
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3
/nix/store/l51240xqsgg8a7yrbqdx1rfzyv6l26fx-lynx-2.8.5

 

Show all paths that directly or indirectly depend on the Glibc (C library) used by svn:

$ nix-store -q --referrers-closure $(ldd $(which svn) | grep /libc.so | awk '{print $3}')
/nix/store/034a6h4vpz9kds5r6kzb9lhh81mscw43-libgnomeprintui-2.8.2
/nix/store/15l3yi0d45prm7a82pcrknxdh6nzmxza-gawk-3.1.4
...

Note that ldd is a command that prints out the dynamic libraries used by an ELF executable.

Make a picture of the runtime dependency graph of the current user environment:

$ nix-store -q --graph ~/.nix-profile | dot -Tps > graph.ps
$ gv graph.ps

 

Show every garbage collector root that points to a store path that depends on svn:

$ nix-store -q --roots $(which svn)
/nix/var/nix/profiles/default-81-link
/nix/var/nix/profiles/default-82-link
/nix/var/nix/profiles/per-user/eelco/profile-97-link

 

Operation --add

Synopsis

nix-store --add paths...

Description

The operation --add adds the specified paths to the Nix store. It prints the resulting paths in the Nix store on standard output.

Example

$ nix-store --add ./foo.c
/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c

Operation --verify

Synopsis

nix-store --verify [--check-contents] [--repair]

Description

The operation --verify verifies the internal consistency of the Nix database, and the consistency between the Nix database and the Nix store. Any inconsistencies encountered are automatically repaired. Inconsistencies are generally the result of the Nix store or database being modified by non-Nix tools, or of bugs in Nix itself.

This operation has the following options:

--check-contents

Checks that the contents of every valid store path has not been altered by computing a SHA-256 hash of the contents and comparing it with the hash stored in the Nix database at build time. Paths that have been modified are printed out. For large stores, --check-contents is obviously quite slow.

--repair

If any valid path is missing from the store, or (if --check-contents is given) the contents of a valid path has been modified, then try to repair the path by redownloading it. See nix-store --repair-path for details.

 

Operation --verify-path

Synopsis

nix-store --verify-path paths...

Description

The operation --verify-path compares the contents of the given store paths to their cryptographic hashes stored in Nix’s database. For every changed path, it prints a warning message. The exit status is 0 if no path has changed, and 1 otherwise.

Example

To verify the integrity of the svn command and all its dependencies:

$ nix-store --verify-path $(nix-store -qR $(which svn))

 

Operation --repair-path

Synopsis

nix-store --repair-path paths...

Description

The operation --repair-path attempts to “repair” the specified paths by redownloading them using the available substituters. If no substitutes are available, then repair is not possible.

Warning: During repair, there is a very small time window during which the old path (if it exists) is moved out of the way and replaced with the new path. If repair is interrupted in between, then the system may be left in a broken state (e.g., if the path contains a critical system component like the GNU C Library).

Example

$ nix-store --verify-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
path `/nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13' was modified!
  expected hash `2db57715ae90b7e31ff1f2ecb8c12ec1cc43da920efcbe3b22763f36a1861588',
  got `481c5aa5483ebc97c20457bb8bca24deea56550d3985cda0027f67fe54b808e4'

$ nix-store --repair-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
fetching path `/nix/store/d7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13'...
…

Operation --dump

Synopsis

nix-store --dump path

Description

The operation --dump produces a NAR (Nix ARchive) file containing the contents of the file system tree rooted at path. The archive is written to standard output.

A NAR archive is like a TAR or Zip archive, but it contains only the information that Nix considers important. For instance, timestamps are elided because all files in the Nix store have their timestamp set to 0 anyway. Likewise, all permissions are left out except for the execute bit, because all files in the Nix store have 644 or 755 permission.

Also, a NAR archive is canonical, meaning that “equal” paths always produce the same NAR archive. For instance, directory entries are always sorted so that the actual on-disk order doesn’t influence the result. This means that the cryptographic hash of a NAR dump of a path is usable as a fingerprint of the contents of the path. Indeed, the hashes of store paths stored in Nix’s database (see nix-store -q --hash) are SHA-256 hashes of the NAR dump of each store path.

NAR archives support filenames of unlimited length and 64-bit file sizes. They can contain regular files, directories, and symbolic links, but not other types of files (such as device nodes).

A Nix archive can be unpacked using nix-store --restore.

Operation --restore

Synopsis

nix-store --restore path

Description

The operation --restore unpacks a NAR archive to path, which must not already exist. The archive is read from standard input.

Operation --export

Synopsis

nix-store --export paths...

Description

The operation --export writes a serialisation of the specified store paths to standard output in a format that can be imported into another Nix store with nix-store --import. This is like nix-store --dump, except that the NAR archive produced by that command doesn’t contain the necessary meta-information to allow it to be imported into another Nix store (namely, the set of references of the path).

This command does not produce a closure of the specified paths, so if a store path references other store paths that are missing in the target Nix store, the import will fail. To copy a whole closure, do something like:

$ nix-store --export $(nix-store -qR paths) > out

To import the whole closure again, run:

$ nix-store --import < out

 

Operation --import

Synopsis

nix-store --import

Description

The operation --import reads a serialisation of a set of store paths produced by nix-store --export from standard input and adds those store paths to the Nix store. Paths that already exist in the Nix store are ignored. If a path refers to another path that doesn’t exist in the Nix store, the import fails.

Operation --optimise

Synopsis

nix-store --optimise

Description

The operation --optimise reduces Nix store disk space usage by finding identical files in the store and hard-linking them to each other. It typically reduces the size of the store by something like 25-35%. Only regular files and symlinks are hard-linked in this manner. Files are considered identical when they have the same NAR archive serialisation: that is, regular files must have the same contents and permission (executable or non-executable), and symlinks must have the same contents.

After completion, or when the command is interrupted, a report on the achieved savings is printed on standard error.

Use -vv or -vvv to get some progress indication.

Example

$ nix-store --optimise
hashing files in `/nix/store/qhqx7l2f1kmwihc9bnxs7rc159hsxnf3-gcc-4.1.1'
...
541838819 bytes (516.74 MiB) freed by hard-linking 54143 files;
there are 114486 files with equal contents out of 215894 files in total

Operation --read-log

Synopsis

nix-store { --read-log | -l } paths...

Description

The operation --read-log prints the build log of the specified store paths on standard output. The build log is whatever the builder of a derivation wrote to standard output and standard error. If a store path is not a derivation, the deriver of the store path is used.

Build logs are kept in /nix/var/log/nix/drvs. However, there is no guarantee that a build log is available for any particular store path. For instance, if the path was downloaded as a pre-built binary through a substitute, then the log is unavailable.

Example

$ nix-store -l $(which ktorrent)
building /nix/store/dhc73pvzpnzxhdgpimsd9sw39di66ph1-ktorrent-2.2.1
unpacking sources
unpacking source archive /nix/store/p8n1jpqs27mgkjw07pb5269717nzf5f8-ktorrent-2.2.1.tar.gz
ktorrent-2.2.1/
ktorrent-2.2.1/NEWS
...

Operation --dump-db

Synopsis

nix-store --dump-db

Description

The operation --dump-db writes a dump of the Nix database to standard output. It can be loaded into an empty Nix store using --load-db. This is useful for making backups and when migrating to different database schemas.

Operation --load-db

Synopsis

nix-store --load-db

Description

The operation --load-db reads a dump of the Nix database created by --dump-db from standard input and loads it into the Nix database.

Operation --print-env

Synopsis

nix-store --print-env drvpath

Description

The operation --print-env prints out the environment of a derivation in a format that can be evaluated by a shell. The command line arguments of the builder are placed in the variable _args.

Example

$ nix-store --print-env $(nix-instantiate '<nixpkgs>' -A firefox)

export src; src='/nix/store/plpj7qrwcz94z2psh6fchsi7s8yihc7k-firefox-12.0.source.tar.bz2'
export stdenv; stdenv='/nix/store/7c8asx3yfrg5dg1gzhzyq2236zfgibnn-stdenv'
export system; system='x86_64-linux'
export _args; _args='-e /nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25c-default-builder.sh'

Operation --generate-binary-cache-key

Synopsis

nix-store --generate-binary-cache-key key-name secret-key-file public-key-file

Description

This command generates an Ed25519 key pair that can be used to create a signed binary cache. It takes three mandatory parameters:

  1. A key name, such as cache.example.org-1, that is used to look up keys on the client when it verifies signatures. It can be anything, but it’s suggested to use the host name of your cache (e.g. cache.example.org) with a suffix denoting the number of the key (to be incremented every time you need to revoke a key).

  2. The file name where the secret key is to be stored.

  3. The file name where the public key is to be stored.

 

Chapter 20. Utilities

This section lists utilities that you can use when you work with Nix.

Name

nix-channel — manage Nix channels

Synopsis

nix-channel { --add url [name] | --remove name | --list | --update [names...] | --rollback [generation] }

Description

A Nix channel is a mechanism that allows you to automatically stay up-to-date with a set of pre-built Nix expressions. A Nix channel is just a URL that points to a place containing both a set of Nix expressions and a pointer to a binary cache. See also Chapter 12, Channels.

This command has the following operations:

--add url [name]

Adds a channel named name with URL url to the list of subscribed channels. If name is omitted, it defaults to the last component of url, with the suffixes -stable or -unstable removed.

--remove name

Removes the channel named name from the list of subscribed channels.

--list

Prints the names and URLs of all subscribed channels on standard output.

--update [names…]

Downloads the Nix expressions of all subscribed channels (or only those included in names if specified) and makes them the default for nix-env operations (by symlinking them from the directory ~/.nix-defexpr).

--rollback [generation]

Reverts the previous call to nix-channel --update. Optionally, you can specify a specific channel generation number to restore.

 

Note that --add does not automatically perform an update.

The list of subscribed channels is stored in ~/.nix-channels.

Examples

To subscribe to the Nixpkgs channel and install the GNU Hello package:

$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --update
$ nix-env -iA nixpkgs.hello

You can revert channel updates using --rollback:

$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.nixpkgsVersion'
"14.04.527.0e935f1"

$ nix-channel --rollback
switching from generation 483 to 482

$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.nixpkgsVersion'
"14.04.526.dbadfad"

Files

/nix/var/nix/profiles/per-user/username/channels

nix-channel uses a nix-env profile to keep track of previous versions of the subscribed channels. Every time you run nix-channel --update, a new channel generation (that is, a symlink to the channel Nix expressions in the Nix store) is created. This enables nix-channel --rollback to revert to previous versions.

~/.nix-defexpr/channels

This is a symlink to /nix/var/nix/profiles/per-user/username/channels. It ensures that nix-env can find your channels. In a multi-user installation, you may also have ~/.nix-defexpr/channels_root, which links to the channels of the root user.

Channel format

A channel URL should point to a directory containing the following files:

nixexprs.tar.xz

A tarball containing Nix expressions and files referenced by them (such as build scripts and patches). At the top level, the tarball should contain a single directory. That directory must contain a file default.nix that serves as the channel’s “entry point”.

binary-cache-url

A file containing the URL to a binary cache (such as https://cache.nixos.org). Nix will automatically check this cache for pre-built binaries, if the user has sufficient rights to add binary caches. For instance, in a multi-user Nix setup, the binary caches provided by the channels of the root user are used automatically, but caches corresponding to the channels of non-root users are ignored.


Name

nix-collect-garbage — delete unreachable store paths

Synopsis

nix-collect-garbage [--delete-old] [-d] [--delete-older-than period] [--max-freed bytes] [--dry-run]

Description

The command nix-collect-garbage is mostly an alias of nix-store --gc, that is, it deletes all unreachable paths in the Nix store to clean up your system. However, it provides two additional options: -d (--delete-old), which deletes all old generations of all profiles in /nix/var/nix/profiles by invoking nix-env --delete-generations old on all profiles (of course, this makes rollbacks to previous configurations impossible); and --delete-older-than period, where period is a value such as 30d, which deletes all generations older than the specified number of days in all profiles in /nix/var/nix/profiles (except for the generations that were active at that point in time).

Example

To delete from the Nix store everything that is not used by the current generations of each profile, do

$ nix-collect-garbage -d

 


Name

nix-copy-closure — copy a closure to or from a remote machine via SSH

Synopsis

nix-copy-closure [ --to | --from ] [--gzip] [--include-outputs] [ --use-substitutes | -s ] [-v[email protected]machine paths

Description

nix-copy-closure gives you an easy and efficient way to exchange software between machines. Given one or more Nix store paths on the local machine, nix-copy-closure computes the closure of those paths (i.e. all their dependencies in the Nix store), and copies all paths in the closure to the remote machine via the ssh (Secure Shell) command. With the --from, the direction is reversed: the closure of paths on a remote machine is copied to the Nix store on the local machine.

This command is efficient because it only sends the store paths that are missing on the target machine.

Since nix-copy-closure calls ssh, you may be asked to type in the appropriate password or passphrase. In fact, you may be asked twice because nix-copy-closure currently connects twice to the remote machine, first to get the set of paths missing on the target machine, and second to send the dump of those paths. If this bothers you, use ssh-agent.

Options

--to

Copy the closure of paths from the local Nix store to the Nix store on machine. This is the default.

--from

Copy the closure of paths from the Nix store on machine to the local Nix store.

--gzip

Enable compression of the SSH connection.

--include-outputs

Also copy the outputs of store derivations included in the closure.

--use-substitutes / -s

Attempt to download missing paths on the target machine using Nix’s substitute mechanism. Any paths that cannot be substituted on the target are still copied normally from the source. This is useful, for instance, if the connection between the source and target machine is slow, but the connection between the target machine and nixos.org (the default binary cache server) is fast.

-v

Show verbose output.

Environment variables

NIX_SSHOPTS

Additional options to be passed to ssh on the command line.

Examples

Copy Firefox with all its dependencies to a remote machine:

$ nix-copy-closure --to [email protected] $(type -tP firefox)

 

Copy Subversion from a remote machine and then install it into a user environment:

$ nix-copy-closure --from [email protected] \
    /nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4
$ nix-env -i /nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4

 


Name

nix-daemon — Nix multi-user support daemon

Synopsis

nix-daemon

Description

The Nix daemon is necessary in multi-user Nix installations. It performs build actions and other operations on the Nix store on behalf of unprivileged users.


Name

nix-hash — compute the cryptographic hash of a path

Synopsis

nix-hash [--flat] [--base32] [--truncate] [--type hashAlgopath...

nix-hash --to-base16 hash...

nix-hash --to-base32 hash...

Description

The command nix-hash computes the cryptographic hash of the contents of each path and prints it on standard output. By default, it computes an MD5 hash, but other hash algorithms are available as well. The hash is printed in hexadecimal. To generate the same hash as nix-prefetch-url you have to specify multiple arguments, see below for an example.

The hash is computed over a serialisation of each path: a dump of the file system tree rooted at the path. This allows directories and symlinks to be hashed as well as regular files. The dump is in the NAR format produced by nix-store --dump. Thus, nix-hash path yields the same cryptographic hash as nix-store --dump path | md5sum.

Options

--flat

Print the cryptographic hash of the contents of each regular file path. That is, do not compute the hash over the dump of path. The result is identical to that produced by the GNU commands md5sum and sha1sum.

--base32

Print the hash in a base-32 representation rather than hexadecimal. This base-32 representation is more compact and can be used in Nix expressions (such as in calls to fetchurl).

--truncate

Truncate hashes longer than 160 bits (such as SHA-256) to 160 bits.

--type hashAlgo

Use the specified cryptographic hash algorithm, which can be one of md5sha1, and sha256.

--to-base16

Don’t hash anything, but convert the base-32 hash representation hash to hexadecimal.

--to-base32

Don’t hash anything, but convert the hexadecimal hash representation hash to base-32.

Examples

Computing the same hash as nix-prefetch-url:

$ nix-prefetch-url file://<(echo test)
1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj
$ nix-hash --type sha256 --flat --base32 <(echo test)
1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj

 

Computing hashes:

$ mkdir test
$ echo "hello" > test/world

$ nix-hash test/ (MD5 hash; default)
8179d3caeff1869b5ba1744e5a245c04

$ nix-store --dump test/ | md5sum (for comparison)
8179d3caeff1869b5ba1744e5a245c04  -

$ nix-hash --type sha1 test/
e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6

$ nix-hash --type sha1 --base32 test/
nvd61k9nalji1zl9rrdfmsmvyyjqpzg4

$ nix-hash --type sha256 --flat test/
error: reading file `test/': Is a directory

$ nix-hash --type sha256 --flat test/world
5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03

 

Converting between hexadecimal and base-32:

$ nix-hash --type sha1 --to-base32 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6
nvd61k9nalji1zl9rrdfmsmvyyjqpzg4

$ nix-hash --type sha1 --to-base16 nvd61k9nalji1zl9rrdfmsmvyyjqpzg4
e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6

 


Name

nix-instantiate — instantiate store derivations from Nix expressions

Synopsis

nix-instantiate [ --parse | --eval [--strict] [--json] [--xml] ] [--read-write-mode] [--arg name value] [ { --attr | -A } attrPath ] [--add-root path] [--indirect] [ --expr | -Efiles...

nix-instantiate --find-file files...

Description

The command nix-instantiate generates store derivations from (high-level) Nix expressions. It evaluates the Nix expressions in each of files (which defaults to ./default.nix). Each top-level expression should evaluate to a derivation, a list of derivations, or a set of derivations. The paths of the resulting store derivations are printed on standard output.

If files is the character -, then a Nix expression will be read from standard input.

See also Chapter 17, Common Options for a list of common options.

Options

--add-root path--indirect

See the corresponding options in nix-store.

--parse

Just parse the input files, and print their abstract syntax trees on standard output in ATerm format.

--eval

Just parse and evaluate the input files, and print the resulting values on standard output. No instantiation of store derivations takes place.

--find-file

Look up the given files in Nix’s search path (as specified by the NIX_PATH environment variable). If found, print the corresponding absolute paths on standard output. For instance, ifNIX_PATH is nixpkgs=/home/alice/nixpkgs, then nix-instantiate --find-file nixpkgs/default.nix will print /home/alice/nixpkgs/default.nix.

--strict

When used with --eval, recursively evaluate list elements and attributes. Normally, such sub-expressions are left unevaluated (since the Nix expression language is lazy).

Warning: This option can cause non-termination, because lazy data structures can be infinitely large.

--json

When used with --eval, print the resulting value as an JSON representation of the abstract syntax tree rather than as an ATerm.

--xml

When used with --eval, print the resulting value as an XML representation of the abstract syntax tree rather than as an ATerm. The schema is the same as that used by the toXML built-in.

--read-write-mode

When used with --eval, perform evaluation in read/write mode so nix language features that require it will still work (at the cost of needing to do instantiation of every evaluated derivation). If this option is not enabled, there may be uninstantiated store paths in the final output.

Examples

Instantiating store derivations from a Nix expression, and building them using nix-store:

$ nix-instantiate test.nix (instantiate)
/nix/store/cigxbmvy6dzix98dxxh9b6shg7ar5bvs-perl-BerkeleyDB-0.26.drv

$ nix-store -r $(nix-instantiate test.nix) (build)
...
/nix/store/qhqk4n8ci095g3sdp93x7rgwyh9rdvgk-perl-BerkeleyDB-0.26 (output path)

$ ls -l /nix/store/qhqk4n8ci095g3sdp93x7rgwyh9rdvgk-perl-BerkeleyDB-0.26
dr-xr-xr-x    2 eelco    users        4096 1970-01-01 01:00 lib
...

 

You can also give a Nix expression on the command line:

$ nix-instantiate -E 'with import <nixpkgs> { }; hello'
/nix/store/j8s4zyv75a724q38cb0r87rlczaiag4y-hello-2.8.drv

This is equivalent to:

$ nix-instantiate '<nixpkgs>' -A hello

 

Parsing and evaluating Nix expressions:

$ nix-instantiate --parse -E '1 + 2'
1 + 2

$ nix-instantiate --eval -E '1 + 2'
3

$ nix-instantiate --eval --xml -E '1 + 2'
<?xml version='1.0' encoding='utf-8'?>
<expr>
  <int value="3" />
</expr>

 

The difference between non-strict and strict evaluation:

$ nix-instantiate --eval --xml -E 'rec { x = "foo"; y = x; }'
...
  <attr name="x">
    <string value="foo" />
  </attr>
  <attr name="y">
    <unevaluated />
  </attr>
...

Note that y is left unevaluated (the XML representation doesn’t attempt to show non-normal forms).

$ nix-instantiate --eval --xml --strict -E 'rec { x = "foo"; y = x; }'
...
  <attr name="x">
    <string value="foo" />
  </attr>
  <attr name="y">
    <string value="foo" />
  </attr>
...

 


Name

nix-prefetch-url — copy a file from a URL into the store and print its hash

Synopsis

nix-prefetch-url [--version] [--type hashAlgo] [--print-path] [--unpack] [--name nameurl [hash]

Description

The command nix-prefetch-url downloads the file referenced by the URL url, prints its cryptographic hash, and copies it into the Nix store. The file name in the store is hash-baseName, where baseName is everything following the final slash in url.

This command is just a convenience for Nix expression writers. Often a Nix expression fetches some source distribution from the network using the fetchurl expression contained in Nixpkgs. However, fetchurl requires a cryptographic hash. If you don't know the hash, you would have to download the file first, and then fetchurl would download it again when you build your Nix expression. Since fetchurl uses the same name for the downloaded file as nix-prefetch-url, the redundant download can be avoided.

If hash is specified, then a download is not performed if the Nix store already contains a file with the same hash and base name. Otherwise, the file is downloaded, and an error if signaled if the actual hash of the file does not match the specified hash.

This command prints the hash on standard output. Additionally, if the option --print-path is used, the path of the downloaded file in the Nix store is also printed.

Options

--type hashAlgo

Use the specified cryptographic hash algorithm, which can be one of md5sha1, and sha256.

--print-path

Print the store path of the downloaded file on standard output.

--unpack

Unpack the archive (which must be a tarball or zip file) and add the result to the Nix store. The resulting hash can be used with functions such as Nixpkgs’s fetchzip orfetchFromGitHub.

--name name

Override the name of the file in the Nix store. By default, this is hash-basename, where basename is the last component of url. Overriding the name is necessary when basename contains characters that are not allowed in Nix store paths.

Examples

$ nix-prefetch-url ftp://ftp.gnu.org/pub/gnu/hello/hello-2.10.tar.gz
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i

$ nix-prefetch-url --print-path mirror://gnu/hello/hello-2.10.tar.gz
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz

$ nix-prefetch-url --unpack --print-path https://github.com/NixOS/patchelf/archive/0.8.tar.gz
079agjlv0hrv7fxnx9ngipx14gyncbkllxrp9cccnh3a50fxcmy7
/nix/store/19zrmhm3m40xxaw81c8cqm6aljgrnwj2-0.8.tar.gz

Chapter 21. Files

This section lists configuration files that you can use when you work with Nix.

Name

nix.conf — Nix configuration file

Description

Nix reads settings from two configuration files:

  • The system-wide configuration file sysconfdir/nix/nix.conf (i.e. /etc/nix/nix.conf on most systems), or $NIX_CONF_DIR/nix.conf if NIX_CONF_DIR is set.

  • The user configuration file $XDG_CONFIG_HOME/nix/nix.conf, or ~/.config/nix/nix.conf if XDG_CONFIG_HOME is not set.

The configuration files consist of name = value pairs, one per line. Other files can be included with a line like include path, where path is interpreted relative to the current conf file and a missing file is an error unless !include is used instead. Comments start with a # character. Here is an example configuration file:

keep-outputs = true       # Nice for developers
keep-derivations = true   # Idem

You can override settings on the command line using the --option flag, e.g. --option keep-outputs false.

The following settings are currently available:

allowed-uris

A list of URI prefixes to which access is allowed in restricted evaluation mode. For example, when set to https://github.com/NixOS, builtin functions such as fetchGit are allowed to access https://github.com/NixOS/patchelf.git.

allow-import-from-derivation

By default, Nix allows you to import from a derivation, allowing building at evaluation time. With this option set to false, Nix will throw an error when evaluating an expression that uses this feature, allowing users to ensure their evaluation will not require any builds to take place.

allow-new-privileges

(Linux-specific.) By default, builders on Linux cannot acquire new privileges by calling setuid/setgid programs or programs that have file capabilities. For example, programs such as sudoor ping will fail. (Note that in sandbox builds, no such programs are available unless you bind-mount them into the sandbox via the sandbox-paths option.) You can allow the use of such programs by enabling this option. This is impure and usually undesirable, but may be useful in certain scenarios (e.g. to spin up containers or set up userspace network interfaces in tests).

allowed-users

A list of names of users (separated by whitespace) that are allowed to connect to the Nix daemon. As with the trusted-users option, you can specify groups by prefixing them with @. Also, you can allow all users by specifying *. The default is *.

Note that trusted users are always allowed to connect.

auto-optimise-store

If set to true, Nix automatically detects files in the store that have identical contents, and replaces them with hard links to a single copy. This saves disk space. If set to false (the default), you can still run nix-store --optimise to get rid of duplicate files.

builders

A list of machines on which to perform builds. See Chapter 16, Remote Builds for details.

builders-use-substitutes

If set to true, Nix will instruct remote build machines to use their own binary substitutes if available. In practical terms, this means that remote hosts will fetch as many build dependencies as possible from their own substitutes (e.g, from cache.nixos.org), instead of waiting for this host to upload them all. This can drastically reduce build times if the network connection between this computer and the remote build host is slow. Defaults to false.

build-users-group

This options specifies the Unix group containing the Nix build user accounts. In multi-user Nix installations, builds should not be performed by the Nix account since that would allow users to arbitrarily modify the Nix store and database by supplying specially crafted builders; and they cannot be performed by the calling user since that would allow him/her to influence the build result.

Therefore, if this option is non-empty and specifies a valid group, builds will be performed under the user accounts that are a member of the group specified here (as listed in /etc/group). Those user accounts should not be used for any other purpose!

Nix will never run two builds under the same user account at the same time. This is to prevent an obvious security hole: a malicious user writing a Nix expression that modifies the build result of a legitimate Nix expression being built by another user. Therefore it is good to have as many Nix build user accounts as you can spare. (Remember: uids are cheap.)

The build users should have permission to create files in the Nix store, but not delete them. Therefore, /nix/store should be owned by the Nix account, its group should be the group specified here, and its mode should be 1775.

If the build users group is empty, builds will be performed under the uid of the Nix process (that is, the uid of the caller if NIX_REMOTE is empty, the uid under which the Nix daemon runs if NIX_REMOTE is daemon). Obviously, this should not be used in multi-user settings with untrusted users.

compress-build-log

If set to true (the default), build logs written to /nix/var/log/nix/drvs will be compressed on the fly using bzip2. Otherwise, they will not be compressed.

connect-timeout

The timeout (in seconds) for establishing connections in the binary cache substituter. It corresponds to curl’s --connect-timeout option.

cores

Sets the value of the NIX_BUILD_CORES environment variable in the invocation of builders. Builders can use this variable at their discretion to control the maximum amount of parallelism. For instance, in Nixpkgs, if the derivation attribute enableParallelBuilding is set to true, the builder passes the -jN flag to GNU Make. It can be overridden using the --corescommand line switch and defaults to 1. The value 0 means that the builder should use all available CPU cores in the system.

extra-sandbox-paths

A list of additional paths appended to sandbox-paths. Useful if you want to extend its default value.

extra-platforms

Platforms other than the native one which this machine is capable of building for. This can be useful for supporting additional architectures on compatible machines: i686-linux can be built on x86_64-linux machines (and the default for this setting reflects this); armv7 is backwards-compatible with armv6 and armv5tel; some aarch64 machines can also natively run 32-bit ARM code; and qemu-user may be used to support non-native platforms (though this may be slow and buggy). Most values for this are not enabled by default because build systems will often misdetect the target platform and generate incompatible code, so you may wish to cross-check the results of using this option against proper natively-built versions of your derivations.

extra-substituters

Additional binary caches appended to those specified in substituters. When used by unprivileged users, untrusted substituters (i.e. those not listed in trusted-substituters) are silently ignored.

fallback

If set to true, Nix will fall back to building from source if a binary substitute fails. This is equivalent to the --fallback flag. The default is false.

fsync-metadata

If set to true, changes to the Nix store metadata (in /nix/var/nix/db) are synchronously flushed to disk. This improves robustness in case of system crashes, but reduces performance. The default is true.

hashed-mirrors

A list of web servers used by builtins.fetchurl to obtain files by hash. The default is http://tarballs.nixos.org/. Given a hash type ht and a base-16 hash h, Nix will try to download the file from hashed-mirror/ht/h. This allows files to be downloaded even if they have disappeared from their original URI. For example, given the default mirrorhttp://tarballs.nixos.org/, when building the derivation

builtins.fetchurl {
  url = https://example.org/foo-1.2.3.tar.xz;
  sha256 = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae";
}

Nix will attempt to download this file from http://tarballs.nixos.org/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae first. If it is not available there, if will try the original URI.

http-connections

The maximum number of parallel TCP connections used to fetch files from binary caches and by other downloads. It defaults to 25. 0 means no limit.

keep-build-log

If set to true (the default), Nix will write the build log of a derivation (i.e. the standard output and error of its builder) to the directory /nix/var/log/nix/drvs. The build log can be retrieved using the command nix-store -l path.

keep-derivations

If true (default), the garbage collector will keep the derivations from which non-garbage store paths were built. If false, they will be deleted unless explicitly registered as a root (or reachable from other roots).

Keeping derivation around is useful for querying and traceability (e.g., it allows you to ask with what dependencies or options a store path was built), so by default this option is on. Turn it off to save a bit of disk space (or a lot if keep-outputs is also turned on).

keep-env-derivations

If false (default), derivations are not stored in Nix user environments. That is, the derivation any build-time-only dependencies may be garbage-collected.

If true, when you add a Nix derivation to a user environment, the path of the derivation is stored in the user environment. Thus, the derivation will not be garbage-collected until the user environment generation is deleted (nix-env --delete-generations). To prevent build-time-only dependencies from being collected, you should also turn on keep-outputs.

The difference between this option and keep-derivations is that this one is “sticky”: it applies to any user environment created while this option was enabled, while keep-derivationsonly applies at the moment the garbage collector is run.

keep-outputs

If true, the garbage collector will keep the outputs of non-garbage derivations. If false (default), outputs will be deleted unless they are GC roots themselves (or reachable from other roots).

In general, outputs must be registered as roots separately. However, even if the output of a derivation is registered as a root, the collector will still delete store paths that are used only at build time (e.g., the C compiler, or source tarballs downloaded from the network). To prevent it from doing so, set this option to true.

max-build-log-size

This option defines the maximum number of bytes that a builder can write to its stdout/stderr. If the builder exceeds this limit, it’s killed. A value of 0 (the default) means that there is no limit.

max-free

This option defines after how many free bytes to stop collecting garbage once the min-free condition gets triggered.

max-jobs

This option defines the maximum number of jobs that Nix will try to build in parallel. The default is 1. The special value auto causes Nix to use the number of CPUs in your system. 0 is useful when using remote builders to prevent any local builds (except for preferLocalBuild derivation attribute which executes locally regardless). It can be overridden using the --max-jobs (-j) command line switch.

max-silent-time

This option defines the maximum number of seconds that a builder can go without producing any data on standard output or standard error. This is useful (for instance in an automated build system) to catch builds that are stuck in an infinite loop, or to catch remote builds that are hanging due to network problems. It can be overridden using the --max-silent-timecommand line switch.

The value 0 means that there is no timeout. This is also the default.

min-free

When the disk reaches min-free bytes of free disk space during a build, nix will start to garbage-collection until max-free bytes are available on the disk. A value of 0 (the default) means that this feature is disabled.

narinfo-cache-negative-ttl

The TTL in seconds for negative lookups. If a store path is queried from a substituter but was not found, there will be a negative lookup cached in the local disk cache database for the specified duration.

narinfo-cache-positive-ttl

The TTL in seconds for positive lookups. If a store path is queried from a substituter, the result of the query will be cached in the local disk cache database including some of the NAR metadata. The default TTL is a month, setting a shorter TTL for positive lookups can be useful for binary caches that have frequent garbage collection, in which case having a more frequent cache invalidation would prevent trying to pull the path again and failing with a hash mismatch if the build isn't reproducible.

netrc-file

If set to an absolute path to a netrc file, Nix will use the HTTP authentication credentials in this file when trying to download from a remote host through HTTP or HTTPS. Defaults to$NIX_CONF_DIR/netrc.

The netrc file consists of a list of accounts in the following format:

machine my-machine
login my-username
password my-password

For the exact syntax, see the curl documentation.

Note: This must be an absolute path, and ~ is not resolved. For example, ~/.netrc won't resolve to your home directory's .netrc.

plugin-files

A list of plugin files to be loaded by Nix. Each of these files will be dlopened by Nix, allowing them to affect execution through static initialization. In particular, these plugins may construct static instances of RegisterPrimOp to add new primops or constants to the expression language, RegisterStoreImplementation to add new store implementations, RegisterCommand to add new subcommands to the nix command, and RegisterSetting to add new nix config settings. See the constructors for those types for more details.

Since these files are loaded into the same address space as Nix itself, they must be DSOs compatible with the instance of Nix running at the time (i.e. compiled against the same headers, not linked to any incompatible libraries). They should not be linked to any Nix libs directly, as those will be available already at load time.

If an entry in the list is a directory, all files in the directory are loaded as plugins (non-recursively).

pre-build-hook

If set, the path to a program that can set extra derivation-specific settings for this system. This is used for settings that can't be captured by the derivation model itself and are too variable between different versions of the same system to be hard-coded into nix.

The hook is passed the derivation path and, if sandboxes are enabled, the sandbox directory. It can then modify the sandbox and send a series of commands to modify various settings to stdout. The currently recognized commands are:

extra-sandbox-paths

Pass a list of files and directories to be included in the sandbox for this build. One entry per line, terminated by an empty line. Entries have the same format as sandbox-paths.

repeat

How many times to repeat builds to check whether they are deterministic. The default value is 0. If the value is non-zero, every build is repeated the specified number of times. If the contents of any of the runs differs from the previous ones, the build is rejected and the resulting store paths are not registered as “valid” in Nix’s database.

require-sigs

If set to true (the default), any non-content-addressed path added or copied to the Nix store (e.g. when substituting from a binary cache) must have a valid signature, that is, be signed using one of the keys listed in trusted-public-keys or secret-key-files. Set to false to disable signature checking.

restrict-eval

If set to true, the Nix evaluator will not allow access to any files outside of the Nix search path (as set via the NIX_PATH environment variable or the -I option), or to URIs outside ofallowed-uri. The default is false.

sandbox

If set to true, builds will be performed in a sandboxed environment, i.e., they’re isolated from the normal file system hierarchy and will only see their dependencies in the Nix store, the temporary build directory, private versions of /proc/dev/dev/shm and /dev/pts (on Linux), and the paths configured with the sandbox-paths option. This is useful to prevent undeclared dependencies on files in directories such as /usr/bin. In addition, on Linux, builds run in private PID, mount, network, IPC and UTS namespaces to isolate them from other processes in the system (except that fixed-output derivations do not run in private network namespace to ensure they can access the network).

Currently, sandboxing only work on Linux and macOS. The use of a sandbox requires that Nix is run as root (so you should use the “build users” feature to perform the actual builds under different users than root).

If this option is set to relaxed, then fixed-output derivations and derivations that have the __noChroot attribute set to true do not run in sandboxes.

The default is false.

sandbox-dev-shm-size

This option determines the maximum size of the tmpfs filesystem mounted on /dev/shm in Linux sandboxes. For the format, see the description of the size option of tmpfs in mount(8). The default is 50%.

sandbox-paths

A list of paths bind-mounted into Nix sandbox environments. You can use the syntax target=source to mount a path in a different location in the sandbox; for instance, /bin=/nix-binwill mount the path /nix-bin as /bin inside the sandbox. If source is followed by ?, then it is not an error if source does not exist; for example, /dev/nvidiactl? specifies that/dev/nvidiactl will only be mounted in the sandbox if it exists in the host filesystem.

Depending on how Nix was built, the default value for this option may be empty or provide /bin/sh as a bind-mount of bash.

secret-key-files

A whitespace-separated list of files containing secret (private) keys. These are used to sign locally-built paths. They can be generated using nix-store --generate-binary-cache-key. The corresponding public key can be distributed to other users, who can add it to trusted-public-keys in their nix.conf.

show-trace

Causes Nix to print out a stack trace in case of Nix expression evaluation errors.

substitute

If set to true (default), Nix will use binary substitutes if available. This option can be disabled to force building from source.

substituters

A list of URLs of substituters, separated by whitespace. The default is https://cache.nixos.org.

system

This option specifies the canonical Nix system name of the current installation, such as i686-linux or x86_64-darwin. Nix can only build derivations whose system attribute equals the value specified here. In general, it never makes sense to modify this value from its default, since you can use it to ‘lie’ about the platform you are building on (e.g., perform a Mac OS build on a Linux machine; the result would obviously be wrong). It only makes sense if the Nix binaries can run on multiple platforms, e.g., ‘universal binaries’ that run on x86_64-linux andi686-linux.

It defaults to the canonical Nix system name detected by configure at build time.

system-features

A set of system “features” supported by this machine, e.g. kvm. Derivations can express a dependency on such features through the derivation attribute requiredSystemFeatures. For example, the attribute

requiredSystemFeatures = [ "kvm" ];

ensures that the derivation can only be built on a machine with the kvm feature.

This setting by default includes kvm if /dev/kvm is accessible, and the pseudo-features nixos-testbenchmark and big-parallel that are used in Nixpkgs to route builds to specific machines.

timeout

This option defines the maximum number of seconds that a builder can run. This is useful (for instance in an automated build system) to catch builds that are stuck in an infinite loop but keep writing to their standard output or standard error. It can be overridden using the --timeout command line switch.

The value 0 means that there is no timeout. This is also the default.

trusted-public-keys

A whitespace-separated list of public keys. When paths are copied from another Nix store (such as a binary cache), they must be signed with one of these keys. For example:cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hydra.nixos.org-1:CNHJZBh9K4tP3EKF6FkkgeVYsS3ohTl+oS0Qa8bezVs=.

trusted-substituters

A list of URLs of substituters, separated by whitespace. These are not used by default, but can be enabled by users of the Nix daemon by specifying --option substituters urls on the command line. Unprivileged users are only allowed to pass a subset of the URLs listed in substituters and trusted-substituters.

trusted-users

A list of names of users (separated by whitespace) that have additional rights when connecting to the Nix daemon, such as the ability to specify additional binary caches, or to import unsigned NARs. You can also specify groups by prefixing them with @; for instance, @wheel means all users in the wheel group. The default is root.

Warning: Adding a user to trusted-users is essentially equivalent to giving that user root access to the system. For example, the user can set sandbox-paths and thereby obtain read access to directories that are otherwise inacessible to them.

 

Deprecated Settings

 

binary-caches

Deprecated: binary-caches is now an alias to substituters.

binary-cache-public-keys

Deprecated: binary-cache-public-keys is now an alias to trusted-public-keys.

build-compress-log

Deprecated: build-compress-log is now an alias to compress-build-log.

build-cores

Deprecated: build-cores is now an alias to cores.

build-extra-chroot-dirs

Deprecated: build-extra-chroot-dirs is now an alias to extra-sandbox-paths.

build-extra-sandbox-paths

Deprecated: build-extra-sandbox-paths is now an alias to extra-sandbox-paths.

build-fallback

Deprecated: build-fallback is now an alias to fallback.

build-max-jobs

Deprecated: build-max-jobs is now an alias to max-jobs.

build-max-log-size

Deprecated: build-max-log-size is now an alias to max-build-log-size.

build-max-silent-time

Deprecated: build-max-silent-time is now an alias to max-silent-time.

build-repeat

Deprecated: build-repeat is now an alias to repeat.

build-timeout

Deprecated: build-timeout is now an alias to timeout.

build-use-chroot

Deprecated: build-use-chroot is now an alias to sandbox.

build-use-sandbox

Deprecated: build-use-sandbox is now an alias to sandbox.

build-use-substitutes

Deprecated: build-use-substitutes is now an alias to substitute.

gc-keep-derivations

Deprecated: gc-keep-derivations is now an alias to keep-derivations.

gc-keep-outputs

Deprecated: gc-keep-outputs is now an alias to keep-outputs.

env-keep-derivations

Deprecated: env-keep-derivations is now an alias to keep-env-derivations.

extra-binary-caches

Deprecated: extra-binary-caches is now an alias to extra-substituters.

trusted-binary-caches

Deprecated: trusted-binary-caches is now an alias to trusted-substituters.

 

Appendix A. Glossary

derivation

A description of a build action. The result of a derivation is a store object. Derivations are typically specified in Nix expressions using the derivation primitive. These are translated into low-level store derivations (implicitly by nix-env and nix-build, or explicitly by nix-instantiate).

store

The location in the file system where store objects live. Typically /nix/store.

store path

The location in the file system of a store object, i.e., an immediate child of the Nix store directory.

store object

A file that is an immediate child of the Nix store directory. These can be regular files, but also entire directory trees. Store objects can be sources (objects copied from outside of the store), derivation outputs (objects produced by running a build action), or derivations (files describing a build action).

substitute

A substitute is a command invocation stored in the Nix database that describes how to build a store object, bypassing the normal build mechanism (i.e., derivations). Typically, the substitute builds the store object by downloading a pre-built version of the store object from some server.

purity

The assumption that equal Nix derivations when run always produce the same output. This cannot be guaranteed in general (e.g., a builder can rely on external inputs such as the network or the system time) but the Nix model assumes it.

Nix expression

A high-level description of software packages and compositions thereof. Deploying software using Nix entails writing Nix expressions for your packages. Nix expressions are translated to derivations that are stored in the Nix store. These derivations can then be built.

reference

A store path P is said to have a reference to a store path Q if the store object at P contains the path Q somewhere. The references of a store path are the set of store paths to which it has a reference.

A derivation can reference other derivations and sources (but not output paths), whereas an output path only references other output paths.

reachable

A store path Q is reachable from another store path P if Q is in the closure of the references relation.

closure

The closure of a store path is the set of store paths that are directly or indirectly “reachable” from that store path; that is, it’s the closure of the path under the references relation. For a package, the closure of its derivation is equivalent to the build-time dependencies, while the closure of its output path is equivalent to its runtime dependencies. For correct deployment it is necessary to deploy whole closures, since otherwise at runtime files could be missing. The command nix-store -qR prints out closures of store paths.

As an example, if the store object at path P contains a reference to path Q, then Q is in the closure of P. Further, if Q references R then R is also in the closure of P.

output path

A store path produced by a derivation.

deriver

The deriver of an output path is the store derivation that built it.

validity

A store path is considered valid if it exists in the file system, is listed in the Nix database as being valid, and if all paths in its closure are also valid.

user environment

An automatically generated store object that consists of a set of symlinks to “active” applications, i.e., other store paths. These are generated automatically by nix-env. See Chapter 10, Profiles.

profile

A symlink to the current user environment of a user, e.g., /nix/var/nix/profiles/default.

NAR

Nix ARchive. This is a serialisation of a path in the Nix store. It can contain regular files, directories and symbolic links. NARs are generated and unpacked using nix-store --dump and nix-store --restore.

Appendix B. Hacking

This section provides some notes on how to hack on Nix. To get the latest version of Nix from GitHub:

$ git clone git://github.com/NixOS/nix.git
$ cd nix

 

To build it and its dependencies:

$ nix-build release.nix -A build.x86_64-linux

 

To build all dependencies and start a shell in which all environment variables are set up so that those dependencies can be found:

$ nix-shell

To build Nix itself in this shell:

[nix-shell]$ ./bootstrap.sh
[nix-shell]$ configurePhase
[nix-shell]$ make

To install it in $(pwd)/inst and test it:

[nix-shell]$ make install
[nix-shell]$ make installcheck