Determinate Nix

Determinate Nix is a downstream distribution of [Nix], a purely functional language, CLI tool, and package management system. It's available on Linux, macOS, and Windows Subsystem for Linux (WSL).

Installing

We recommend that macOS users install Determinate Nix using our graphical installer, Determinate.pkg. For Linux and Windows Subsystem for Linux (WSL) users:

curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | \
  sh -s -- install --determinate

How Nix works

Nix treats packages like values in purely functional programming languages such as Haskell — they are built by functions that don’t have side-effects, and they never change after they have been built. Nix stores packages in the Nix store, usually the directory /nix/store, where each package has its own unique subdirectory such as

/nix/store/b6gvzjyb2pg0kjfwrjmg1vfhh54ad73z-firefox-33.1/

where b6gvzjyb2pg0… is a unique identifier for the package that captures all its dependencies (it’s a cryptographic hash of the package’s build dependency graph). This enables many powerful features.

Multiple versions

You can have multiple versions or variants of a package installed at the same time. This is especially important when different applications have dependencies on different versions of the same package — it prevents the “DLL hell”. Because of the hashing scheme, different versions of a package end up in different paths in the Nix store, so they don’t interfere with each other.

An important consequence is that operations like upgrading or uninstalling an application cannot break other applications, since these operations never “destructively” update or delete files that are used by other packages.

Complete dependencies

Nix helps you make sure that package dependency specifications are complete. In general, when you’re making a package for a package management system like RPM, you have to specify for each package what its dependencies are, but there are no guarantees that this specification is complete. If you forget a dependency, then the package will build and work correctly on your machine if you have the dependency installed, but not on the end user's machine if it's not there.

Since Nix on the other hand doesn’t install packages in “global” locations like /usr/bin but in package-specific directories, the risk of incomplete dependencies is greatly reduced. This is because tools such as compilers don’t search in per-packages directories such as /nix/store/5lbfaxb722zp…-openssl-0.9.8d/include, so if a package builds correctly on your system, this is because you specified the dependency explicitly. This takes care of the build-time dependencies.

Once a package is built, runtime dependencies are found by scanning binaries for the hash parts of Nix store paths (such as r8vvq9kq…). This sounds risky, but it works extremely well.

Multi-user support

Nix has multi-user support. This means that non-privileged users can securely install software. Each user can have a different profile, a set of packages in the Nix store that appear in the user’s PATH. If a user installs a package that another user has already installed previously, the package won’t be built or downloaded a second time. At the same time, it is not possible for one user to inject a Trojan horse into a package that might be used by another user.

Atomic upgrades and rollbacks

Since package management operations never overwrite packages in the Nix store but just add new versions in different paths, they are atomic. So during a package upgrade, there is no time window in which the package has some files from the old version and some files from the new version — which would be bad because a program might well crash if it’s started during that period.

And since packages aren’t overwritten, the old versions are still there after an upgrade. This means that you can roll back to the old version:

$ nix-env --upgrade --attr nixpkgs.some-package
$ nix-env --rollback

Garbage collection

When you uninstall a package like this…

$ nix-env --uninstall firefox

the package isn’t deleted from the system right away (after all, you might want to do a rollback, or it might be in the profiles of other users). Instead, unused packages can be deleted safely by running the garbage collector:

$ nix-collect-garbage

This deletes all packages that aren’t in use by any user profile or by a currently running program.

Functional package language

Packages are built from Nix expressions, which is a simple functional language. A Nix expression describes everything that goes into a package build task (a “derivation”): other packages, sources, the build script, environment variables for the build script, etc. Nix tries very hard to ensure that Nix expressions are deterministic: building a Nix expression twice should yield the same result.

Because it’s a functional language, it’s easy to support building variants of a package: turn the Nix expression into a function and call it any number of times with the appropriate arguments. Due to the hashing scheme, variants don’t conflict with each other in the Nix store.

Transparent source/binary deployment

Nix expressions generally describe how to build a package from source, so an installation action like

$ nix-env --install --attr nixpkgs.firefox

could cause quite a bit of build activity, as not only Firefox but also all its dependencies (all the way up to the C library and the compiler) would have to be built, at least if they are not already in the Nix store. This is a source deployment model. For most users, building from source is not very pleasant as it takes far too long. However, Nix can automatically skip building from source and instead use a binary cache, a web server that provides pre-built binaries. For instance, when asked to build /nix/store/b6gvzjyb2pg0…-firefox-33.1 from source, Nix would first check if the file https://cache.nixos.org/b6gvzjyb2pg0….narinfo exists, and if so, fetch the pre-built binary referenced from there; otherwise, it would fall back to building from source.

Nix Packages collection

We provide a large set of Nix expressions containing hundreds of existing Unix packages, the Nix Packages collection (Nixpkgs).

Managing build environments

Nix is extremely useful for developers as it makes it easy to automatically set up the build environment for a package. Given a Nix expression that describes the dependencies of your package, the command nix-shell will build or download those dependencies if they’re not already in your Nix store, and then start a Bash shell in which all necessary environment variables (such as compiler search paths) are set.

For example, the following command gets all dependencies of the Pan newsreader, as described by its Nix expression:

$ nix-shell '<nixpkgs>' --attr pan

You’re then dropped into a shell where you can edit, build and test the package:

[nix-shell]$ unpackPhase
[nix-shell]$ cd pan-*
[nix-shell]$ configurePhase
[nix-shell]$ buildPhase
[nix-shell]$ ./pan/gui/pan

Portability

Nix runs on Linux and macOS.

NixOS

NixOS is a Linux distribution based on Nix. It uses Nix not just for package management but also to manage the system configuration (e.g., to build configuration files in /etc). This means, among other things, that it is easy to roll back the entire configuration of the system to an earlier state. Also, users can install software without root privileges. For more information and downloads, see the [NixOS homepage][nix].

License

Nix is released under the terms of the GNU LGPLv2.1 or (at your option) any later version.

Quick Start

This chapter is for impatient people who don't like reading documentation. For more in-depth information you are kindly referred to subsequent chapters.

  1. Install Nix. We recommend that macOS users install Determinate Nix using our graphical installer, Determinate.pkg. For Linux and Windows Subsystem for Linux (WSL) users:

    $ curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | \
      sh -s -- install --determinate
    

    The install script will use sudo, so make sure you have sufficient rights.

    For other installation methods, see the detailed installation instructions.

  2. Run software without installing it permanently:

    $ nix-shell --packages cowsay lolcat
    

    This downloads the specified packages with all their dependencies, and drops you into a Bash shell where the commands provided by those packages are present. This will not affect your normal environment:

    [nix-shell:~]$ cowsay Hello, Nix! | lolcat
    

    Exiting the shell will make the programs disappear again:

    [nix-shell:~]$ exit
    $ lolcat
    lolcat: command not found
    
  3. Search for more packages on search.nixos.org to try them out.

  4. Free up storage space:

    $ nix-collect-garbage
    

Installation

We recommend that macOS users install Determinate Nix using our graphical installer, Determinate.pkg. For Linux and Windows Subsystem for Linux (WSL) users:

curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | \
  sh -s -- install --determinate

Distributions

The Nix community maintains installers for several distributions.

They can be found in the nix-community/nix-installers repository.

Installing Nix from Source

If no binary package is available or if you want to hack on Nix, you can build Nix from its Git repository.

Prerequisites

  • GNU Autoconf (https://www.gnu.org/software/autoconf/) and the autoconf-archive macro collection (https://www.gnu.org/software/autoconf-archive/). These are needed to run the bootstrap script.

  • GNU Make.

  • Bash Shell. The ./configure script relies on bashisms, so Bash is required.

  • A version of GCC or Clang that supports C++20.

  • pkg-config to locate dependencies. If your distribution does not provide it, you can get it from http://www.freedesktop.org/wiki/Software/pkg-config.

  • The OpenSSL library to calculate cryptographic hashes. If your distribution does not provide it, you can get it from https://www.openssl.org.

  • The libbrotlienc and libbrotlidec libraries to provide implementation of the Brotli compression algorithm. They are available for download from the official repository https://github.com/google/brotli.

  • cURL and its library. If your distribution does not provide it, you can get it from https://curl.haxx.se/.

  • The SQLite embedded database library, version 3.6.19 or higher. If your distribution does not provide it, please install it from http://www.sqlite.org/.

  • The Boehm garbage collector (bdw-gc) to reduce the evaluator’s memory consumption (optional).

    To enable it, install pkgconfig and the Boehm garbage collector, and pass the flag --enable-gc to configure.

  • The boost library of version 1.66.0 or higher. It can be obtained from the official web site https://www.boost.org/.

  • The editline library of version 1.14.0 or higher. It can be obtained from the its repository https://github.com/troglobit/editline.

  • The libsodium library for verifying cryptographic signatures of contents fetched from binary caches. It can be obtained from the official web site https://libsodium.org.

  • Recent versions of Bison and Flex to build the parser. (This is because Nix needs GLR support in Bison and reentrancy support in Flex.) For Bison, you need version 2.6, which can be obtained from the GNU FTP server. For Flex, you need version 2.5.35, which is available on SourceForge. Slightly older versions may also work, but ancient versions like the ubiquitous 2.5.4a won't.

  • The libseccomp is used to provide syscall filtering on Linux. This is an optional dependency and can be disabled passing a --disable-seccomp-sandboxing option to the configure script (Not recommended unless your system doesn't support libseccomp). To get the library, visit https://github.com/seccomp/libseccomp.

  • On 64-bit x86 machines only, libcpuid library is used to determine which microarchitecture levels are supported (e.g., as whether to have x86_64-v2-linux among additional system types). The library is available from its homepage http://libcpuid.sourceforge.net. This is an optional dependency and can be disabled by providing a --disable-cpuid to the configure script.

  • Unless ./configure --disable-unit-tests is specified, GoogleTest (GTest) and RapidCheck are required, which are available at https://google.github.io/googletest/ and https://github.com/emil-e/rapidcheck respectively.

Obtaining the Source

The most recent sources of Nix can be obtained from its Git repository. For example, the following command will check out the latest revision into a directory called nix:

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

Likewise, specific releases can be obtained from the tags of the repository.

Building Nix from Source

Nix is built with Meson. It is broken up into multiple Meson packages, which are optionally combined in a single project using Meson's subprojects feature.

There are no mandatory extra steps to the building process: generic Meson installation instructions like this should work.

The installation path can be specified by passing the -Dprefix=prefix to configure. The default installation directory is /usr/local. You can change this to any location you like. You must have write permission to the prefix path.

Nix keeps its store (the place where packages are stored) in /nix/store by default. This can be changed using -Dstore-dir=path.

Warning

It is best not to change the Nix store from its default, since doing so makes it impossible to use pre-built binaries from the standard Nixpkgs channels — that is, all packages will need to be built from source.

Nix keeps state (such as its database and log files) in /nix/var by default. This can be changed using -Dlocalstatedir=path.

Using Nix within Docker

To run the latest stable release of Nix with Docker run the following command:

$ docker run -ti ghcr.io/nixos/nix
Unable to find image 'ghcr.io/nixos/nix:latest' locally
latest: Pulling from ghcr.io/nixos/nix
5843afab3874: Pull complete
b52bf13f109c: Pull complete
1e2415612aa3: Pull complete
Digest: sha256:27f6e7f60227e959ee7ece361f75d4844a40e1cc6878b6868fe30140420031ff
Status: Downloaded newer image for ghcr.io/nixos/nix:latest
35ca4ada6e96:/# nix --version
nix (Nix) 2.3.12
35ca4ada6e96:/# exit

What is included in Nix's Docker image?

The official Docker image is created using pkgs.dockerTools.buildLayeredImage (and not with Dockerfile as it is usual with Docker images). You can still base your custom Docker image on it as you would do with any other Docker image.

The Docker image is also not based on any other image and includes minimal set of runtime dependencies that are required to use Nix:

  • pkgs.nix
  • pkgs.bashInteractive
  • pkgs.coreutils-full
  • pkgs.gnutar
  • pkgs.gzip
  • pkgs.gnugrep
  • pkgs.which
  • pkgs.curl
  • pkgs.less
  • pkgs.wget
  • pkgs.man
  • pkgs.cacert.out
  • pkgs.findutils

Docker image with the latest development version of Nix

To get the latest image that was built by Hydra run the following command:

$ curl -L https://hydra.nixos.org/job/nix/master/dockerImage.x86_64-linux/latest/download/1 | docker load
$ docker run -ti nix:2.5pre20211105

You can also build a Docker image from source yourself:

$ nix build ./\#hydraJobs.dockerImage.x86_64-linux
$ docker load -i ./result/image.tar.gz
$ docker run -ti nix:2.5pre20211105

Docker image with non-root Nix

If you would like to run Nix in a container under a user other than root, you can build an image with a non-root single-user installation of Nix by specifying the uid, gid, uname, and gname arguments to docker.nix:

$ nix build --file docker.nix \
    --arg uid 1000 \
    --arg gid 1000 \
    --argstr uname user \
    --argstr gname user \
    --argstr name nix-user \
    --out-link nix-user.tar.gz
$ docker load -i nix-user.tar.gz
$ docker run -ti nix-user

Security

Nix follows a multi-user security model in which all users can perform package management operations. Every user can, for example, install software without requiring root privileges, and Nix ensures that this is secure. It's not possible for one user to, for example, overwrite a package used by another user with a Trojan horse.

Multi-User model

To allow a Nix store to be shared safely among multiple users, it is important that users are not able to run builders that modify the Nix store or database in arbitrary ways, or that interfere with builds started by other users. If they could do so, they could install a Trojan horse in some package and compromise the accounts of other users.

To prevent this, the Nix store and database are owned by some privileged user (usually root) and builders are executed under special user accounts (usually named nixbld1, nixbld2, etc.). When a unprivileged user runs a Nix command, actions that operate on the Nix store (such as builds) are forwarded to a Nix daemon running under the owner of the Nix store/database that performs the operation.

Note

Multi-user mode has one important limitation: only root and a set of trusted users specified in nix.conf can specify arbitrary binary caches. So while unprivileged users may install packages from arbitrary Nix expressions, they may not get pre-built binaries.

Setting up the build users

The build users are the special UIDs under which builds are performed. They should all be members of the build users group nixbld. This group should have no other members. The build users should not be members of any other group. On Linux, you can create the group and users as follows:

$ groupadd -r nixbld
$ for n in $(seq 1 10); do useradd -c "Nix build user $n" \
    -d /var/empty -g nixbld -G nixbld -M -N -r -s "$(which nologin)" \
    nixbld$n; done

This creates 10 build users. There can never be more concurrent builds than the number of build users, so you may want to increase this if you expect to do many builds at the same time.

Running the daemon

The Nix daemon should be started as follows (as root):

$ nix-daemon

You’ll want to put that line somewhere in your system’s boot scripts.

To let unprivileged users use the daemon, they should set the NIX_REMOTE environment variable to daemon. So you should put a line like

export NIX_REMOTE=daemon

into the users’ login scripts.

Restricting access

To limit which users can perform Nix operations, you can use the permissions on the directory /nix/var/nix/daemon-socket. For instance, if you want to restrict the use of Nix to the members of a group called nix-users, do

$ chgrp nix-users /nix/var/nix/daemon-socket
$ chmod ug=rwx,o= /nix/var/nix/daemon-socket

This way, users who are not in the nix-users group cannot connect to the Unix domain socket /nix/var/nix/daemon-socket/socket, so they cannot perform Nix operations.

Upgrading Nix

You can upgrade Determinate Nix using Determinate Nixd:

sudo determinate-nixd upgrade

Note that the sudo is necessary here and upgrading fails without it.

Uninstalling Nix

To uninstall Determinate Nix, use the uninstallation utility built into the Determinate Nix Installer:

$ /nix/nix-installer uninstall

If you're certain that you want to uninstall, you can skip the confirmation step:

$ /nix/nix-installer uninstall --no-confirm

Nix Store

The Nix store is an abstraction to store immutable file system data (such as software packages) that can have dependencies on other such data.

There are multiple types of Nix stores with different capabilities, such as the default one on the local filesystem (/nix/store) or binary caches.

File System Object

Nix uses a simplified model of the file system, which consists of file system objects. Every file system object is one of the following:

  • File

    • A possibly empty sequence of bytes for contents
    • A single boolean representing the executable permission
  • Directory

    Mapping of names to child file system objects

  • Symbolic link

    An arbitrary string. Nix does not assign any semantics to symbolic links.

File system objects and their children form a tree. A bare file or symlink can be a root file system object.

Nix does not encode any other file system notions such as hard links, permissions, timestamps, or other metadata.

Examples of file system objects

A plain file:

50 B, executable: false

An executable file:

122 KB, executable: true

A symlink:

-> /usr/bin/sh

A directory with contents:

├── bin
│   └── hello: 35 KB, executable: true
└── share
    ├── info
    │   └── hello.info: 36 KB, executable: false
    └── man
        └── man1
            └── hello.1.gz: 790 B, executable: false

A directory that contains a symlink and other directories:

├── bin -> share/go/bin
├── nix-support/
└── share/

Content-Addressing File System Objects

For many operations, Nix needs to calculate a content addresses of a file system object (FSO). Usually this is needed as part of content addressing store objects, since store objects always have a root file system object. But some command-line utilities also just work on "raw" file system objects, not part of any store object.

Every content addressing scheme Nix uses ultimately involves feeding data into a hash function, and getting back an opaque fixed-size digest which is deemed a content address. The various methods of content addressing thus differ in how abstract data (in this case, a file system object and its descendants) are fed into the hash function.

Serialising File System Objects

The simplest method is to serialise the entire file system object tree into a single binary string, and then hash that binary string, yielding the content address. In this section we describe the currently-supported methods of serialising file system objects.

Flat

A single file object can just be hashed by its contents. This is not enough information to encode the fact that the file system object is a file, but if we already know that the FSO is a single non-executable file by other means, it is sufficient.

Because the hashed data is just the raw file, as is, this choice is good for compatibility with other systems. For example, Unix commands like sha256sum or sha1sum will produce hashes for single files that match this.

Nix Archive (NAR)

For the other cases of file system objects, especially directories with arbitrary descendants, we need a more complex serialisation format. Examples of such serialisations are the ZIP and TAR file formats. However, for our purposes these formats have two problems:

  • They do not have a canonical serialisation, meaning that given an FSO, there can be many different serialisations. For instance, TAR files can have variable amounts of padding between archive members; and some archive formats leave the order of directory entries undefined. This would be bad because we use serialisation to compute cryptographic hashes over file system objects, and for those hashes to be useful as a content address or for integrity checking, uniqueness is crucial. Otherwise, correct hashes would report false mismatches, and the store would fail to find the content.

  • They store more information than we have in our notion of FSOs, such as time stamps. This can cause FSOs that Nix should consider equal to hash to different values on different machines, just because the dates differ.

  • As a practical consideration, the TAR format is the only truly universal format in the Unix environment. It has many problems, such as an inability to deal with long file names and files larger than 2^33 bytes. Current implementations such as GNU Tar work around these limitations in various ways.

For these reasons, Nix has its very own archive format—the Nix Archive (NAR) format, which is carefully designed to avoid the problems described above.

The exact specification of the Nix Archive format is in protocols/nix-archive.md

Content addressing File System Objects beyond a single serialisation pass

Serialising the entire tree and then hashing that binary string is not the only option for content addressing, however. Another technique is that of a Merkle graph, where previously computed hashes are included in subsequent byte strings to be hashed.

In particular, the Merkle graphs can match the original graph structure of file system objects: we can first hash (serialised) child file system objects, and then hash parent objects using the hashes of their children in the serialisation (to be hashed) of the parent file system objects.

Currently, there is one such Merkle DAG content addressing method supported.

Git (experimental)

Warning

This method is part of the git-hashing experimental feature.

Git's file system model is very close to Nix's, and so Git's content addressing method is a pretty good fit. Just as with regular Git, files and symlinks are hashed as git "blobs", and directories are hashed as git "trees".

However, one difference between Nix's and Git's file system model needs special treatment. Plain files, executable files, and symlinks are not differentiated as distinctly addressable objects, but by their context: by the directory entry that refers to them. That means so long as the root object is a directory, there is no problem: every non-directory object is owned by a parent directory, and the entry that refers to it provides the missing information. However, if the root object is not a directory, then we have no way of knowing which one of an executable file, non-executable file, or symlink it is supposed to be.

In response to this, we have decided to treat a bare file as non-executable file. This is similar to do what we do with flat serialisation, which also lacks this information. To avoid an address collision, attempts to hash a bare executable file or symlink will result in an error (just as would happen for flat serialisation also). Thus, Git can encode some, but not all of Nix's "File System Objects", and this sort of content-addressing is likewise partial.

In the future, we may support a Git-like hash for such file system objects, or we may adopt another Merkle DAG format which is capable of representing all Nix file system objects.

Store Object

A Nix store is a collection of store objects with references between them. A store object consists of

Store objects are immutable: Once created, they do not change until they are deleted.

Content-Addressing Store Objects

Just like File System Objects, Store Objects can also be content-addressed, unless they are input-addressed.

For store objects, the content address we produce will take the form of a Store Path rather than regular hash. In particular, the content-addressing scheme will ensure that the digest of the store path is solely computed from the

  • file system object graph (the root one and its children, if it has any)
  • references
  • store directory
  • name

of the store object, and not any other information, which would not be an intrinsic property of that store object.

For the full specification of the algorithms involved, see the specification of store path digests.

Content addressing each part of a store object

File System Objects

With all currently-supported store object content-addressing methods, the file system object is always content-addressed first, and then that hash is incorporated into content address computation for the store object.

References

References to other store objects

With all currently supported store object content addressing methods, other objects are referred to by their regular (string-encoded-) store paths.

Self-references

Self-references however cannot be referred to by their path, because we are in the midst of describing how to compute that path!

The alternative would require finding as hash function fixed point, i.e. the solution to an equation in the form

digest = hash(..... || digest || ....)

which is computationally infeasible. As far as we know, this is equivalent to finding a hash collision.

Instead we have a "has self-reference" boolean, which ends up affecting the digest: In all currently-supported store object content-addressing methods, when hashing the file system object data, any occurence of store object's own store path in the digested data is replaced with a sentinel value. The hashes of these modified input streams are used instead.

When validating the content address of a store object after the fact, the above process works as written. However, when first creating the store object we don't know the store object's store path, as explained just above. We therefore, strictly speaking, do not know what value we will be replacing with the sentinental value in the inputs to hash functions. What instead happens is that the provisional store object --- the data from which we wish to create a store object --- is paired with a provisional "scratch" store path (that presumably was chosen when the data was created). That provisional store path is instead what is replaced with the sentinel value, rather than the final store object which we do not yet know.

Design note

It is an informal property of content-addressed store objects that the choice of provisional store path should not matter. In other words, if a provisional store object is prepared in the same way except for the choice of provision store path, the provisional data need not be identical. But, after the sentinel value is substituted in place of each provisional store object's provision store path, the final so-normalized data should be identical.

If, conversely, the data after this normalization process is still different, we'll compute a different content-address. The method of preparing the provisional self-referenced data has failed to be deterministic in the sense of not leaking the choice of provisional store path --- a choice which is supposed to be arbitrary --- into the final store object.

This property is informal because at this stage, we are just described store objects, which have no formal notion of their origin. Without such a formal notion, there is nothing to formally accuse of being insufficiently deterministic. Where we cover derivations, we will have a chance to make this a formal property, not of content-addressed store objects themselves, but of derivations that produce content-addressed store objects.

Name and Store Directory

These two items affect the digest in a way that is standard for store path digest computations and not specific to content-addressing. Consult the specification of store path digests for further details.

Content addressing Methods

For historical reasons, we don't support all features in all combinations. Each currently supported method of content addressing chooses a single method of file system object hashing, and may offer some restrictions on references. The names and store directories are unrestricted however.

Flat

This uses the corresponding Flat method of file system object content addressing.

References are not supported: store objects with flat hashing and references can not be created.

Text

This also uses the corresponding Flat method of file system object content addressing.

References to other store objects are supported, but self-references are not.

This is the only store-object content-addressing method that is not named identically with a corresponding file system object method. It is somewhat obscure, mainly used for "drv files" (derivations serialized as store objects in their "ATerm" file format). Prefer another method if possible.

Nix Archive

This uses the corresponding Nix Archive method of file system object content addressing.

References (to other store objects and self-references alike) are supported so long as the hash algorithm is SHA-256, but not (neither kind) otherwise.

Git

Warning

This method is part of the git-hashing experimental feature.

This uses the corresponding Git method of file system object content addressing.

References are not supported.

Only SHA-1 is supported at this time. If SHA-256-based Git becomes more widespread, this restriction will be revisited.

Store Path

Example

/nix/store/a040m110amc4h71lds2jmr8qrkj2jhxd-git-2.38.1

A rendered store path

Nix implements references to store objects as store paths.

Think of a store path as an opaque, unique identifier: The only way to obtain store path is by adding or building store objects. A store path will always reference exactly one store object.

Store paths are pairs of

  • A 20-byte digest for identification
  • A symbolic name for people to read

Example

  • Digest: b6gvzjyb2pg0kjfwrjmg1vfhh54ad73z
  • Name: firefox-33.1

To make store objects accessible to operating system processes, stores have to expose store objects through the file system.

A store path is rendered to a file system path as the concatenation of

  • Store directory (typically /nix/store)
  • Path separator (/)
  • Digest rendered in a custom variant of Base32 (20 arbitrary bytes become 32 ASCII characters)
  • Hyphen (-)
  • Name

Example

  /nix/store/b6gvzjyb2pg0kjfwrjmg1vfhh54ad73z-firefox-33.1
  |--------| |------------------------------| |----------|
store directory            digest                 name

Exactly how the digest is calculated depends on the type of store path. Store path digests are supposed to be opaque, and so for most operations, it is not necessary to know the details. That said, the manual has a full specification of store path digests.

Store Directory

Every Nix store has a store directory.

Not every store can be accessed through the file system. But if the store has a file system representation, the store directory contains the store’s file system objects, which can be addressed by store paths.

This means a store path is not just derived from the referenced store object itself, but depends on the store that the store object is in.

Note

The store directory defaults to /nix/store, but is in principle arbitrary.

It is important which store a given store object belongs to: Files in the store object can contain store paths, and processes may read these paths. Nix can only guarantee referential integrity if store paths do not cross store boundaries.

Therefore one can only copy store objects to a different store if

  • The source and target stores' directories match

    or

  • The store object in question has no references, that is, contains no store paths

One cannot copy a store object to a store with a different store directory. Instead, it has to be rebuilt, together with all its dependencies. It is in general not enough to replace the store directory string in file contents, as this may render executables unusable by invalidating their internal offsets or checksums.

Store Derivation and Deriving Path

Besides functioning as a content-addressed store, the Nix store layer works as a build system. Other systems (like Git or IPFS) also store and transfer immutable data, but they don't concern themselves with how that data was created.

This is where Nix distinguishes itself. Derivations represent individual build steps, and deriving paths are needed to refer to the outputs of those build steps before they are built.

Store Derivation

A derivation is a specification for running an executable on precisely defined input to produce on more store objects. These store objects are known as the derivation's outputs.

Derivations are built, in which case the process is spawned according to the spec, and when it exits, required to leave behind files which will (after post-processing) become the outputs of the derivation. This process is described in detail in Building.

A derivation consists of:

Referencing derivations

Derivations are always referred to by the store path of the store object they are encoded to. See the encoding section for more details on how this encoding works, and thus what exactly what store path we would end up with for a given derivation.

The store path of the store object which encodes a derivation is often called a derivation path for brevity.

Deriving path

Deriving paths are a way to refer to store objects that may or may not yet be realised. There are two forms:

In pseudo code:

type OutputName = String;

type ConstantPath = {
  path: StorePath;
};

type OutputPath = {
  drvPath: StorePath;
  output: OutputName;
};

type DerivingPath = ConstantPath | OutputPath;

Deriving paths are necessary because, in general and particularly for content-addressing derivations, the store path of an output is not known in advance. We can use an output deriving path to refer to such an output, instead of the store path which we do not yet know.

Parts of a derivation

A derivation is constructed from the parts documented in the following subsections.

Inputs

The inputs are a set of deriving paths, referring to all store objects needed in order to perform this build step.

The process creation fields will presumably include many store paths:

  • The path to the executable normally starts with a store path
  • The arguments and environment variables likely contain many other store paths.

But rather than somehow scanning all the other fields for inputs, Nix requires that all inputs be explicitly collected in the inputs field. It is instead the responsibility of the creator of a derivation (e.g. the evaluator) to ensure that every store object referenced in another field (e.g. referenced by store path) is included in this inputs field.

System

The system type on which the builder executable is meant to be run.

A necessary condition for Nix to schedule a given derivation on some Nix instance is for the "system" of that derivation to match that instance's system configuration option or extra-platforms configuration option.

By putting the system in each derivation, Nix allows heterogenous build plans, where not all steps can be run on the same machine or same sort of machine. Nix can schedule builds such that it automatically builds on other platforms by forwarding build requests to other Nix instances.

Process creation fields

These are the three fields which describe how to spawn the process which (along with any of its own child processes) will perform the build. You may note that this has everything needed for an execve system call.

Builder

This is the path to an executable that will perform the build and produce the outputs.

Arguments

Command-line arguments to be passed to the builder executable.

Note that these are the arguments after the first argument. The first argument passed to the builder will be the value of builder, as per the usual convention on Unix. See Wikipedia for details.

Environment Variables

Environment variables which will be passed to the builder executable.

Placeholders

Placeholders are opaque values used within the process creation fields to [store objects] for which we don't yet know store paths. They are strings in the form /<hash> that are embedded anywhere within the strings of those fields, and we are considering to add store-path-like placeholders.

Note

Output Deriving Path exist to solve the same problem as placeholders --- that is, referring to store objects for which we don't yet know a store path. They also have a string syntax with ^, described in the encoding section. We could use that syntax instead of /<hash> for placeholders, but its human-legibility would cause problems.

There are two types of placeholder, corresponding to the two cases where this problem arises:

  • Output placeholder:

    This is a placeholder for a derivation's own output.

  • Input placeholder:

    This is a placeholder to a derivation's non-constant input, i.e. an input that is an [output derived path].

Explanation

In general, we need to realise realise a store object in order to be sure to have a store object for it. But for these two cases this is either impossible or impractical:

  • In the output case this is impossible:

    We cannot build the output until we have a correct derivation, and we cannot have a correct derivation (without using placeholders) until we have the output path.

  • In the input case this is impractical:

    If we always build a dependency first, and then refer to its output by store path, we would lose the ability for a derivation graph to describe an entire build plan consisting of multiple build steps.

Encoding

Derivation

There are two formats, documented separately:

Every derivation has a canonical choice of encoding used to serialize it to a store object. This ensures that there is a canonical store path used to refer to the derivation, as described in Referencing derivations.

Note

Currently, the canonical encoding for every derivation is the "ATerm" format, but this is subject to change for types derivations which are not yet stable.

Regardless of the format used, when serializing a derivation to a store object, that store object will be content-addressed.

In the common case, the inputs to store objects are either:

  • constant deriving paths for content-addressed source objects, which are "initial inputs" rather than the outputs of some other derivation

  • the outputs of other derivations

If those other derivations also abide by this common case (and likewise for transitive inputs), then the entire closure of the serialized derivation will be content-addressed.

Deriving Path

  • constant

    Constant deriving paths are encoded simply as the underlying store path is. Thus, we see that every encoded store path is also a valid encoded (constant) deriving path.

  • output

    Output deriving paths are encoded by

    • encoding of a store path referring to a derivation

    • a ^ separator (or ! in some legacy contexts)

    • the name of an output of the previously referred derivation

    Example

    /nix/store/lxrn8v5aamkikg6agxwdqd1jz7746wz4-firefox-98.0.2.drv^out
    

    This parses like so:

    /nix/store/lxrn8v5aamkikg6agxwdqd1jz7746wz4-firefox-98.0.2.drv^out
    |------------------------------------------------------------| |-|
    store path (usual encoding)                                    output name
                                                              |--|
                                                              note the ".drv"
    

Extending the model to be higher-order

Experimental feature: dynamic-derivations

So far, we have used store paths to refer to derivations. That works because we've implicitly assumed that all derivations are created statically --- created by some mechanism out of band, and then manually inserted into the store. But what if derivations could also be created dynamically within Nix? In other words, what if derivations could be the outputs of other derivations?

Note

In the parlance of "Build Systems à la carte", we are generalizing the Nix store layer to be a "Monadic" instead of "Applicative" build system.

How should we refer to such derivations? A deriving path works, the same as how we refer to other derivation outputs. But what about a dynamic derivations output? (i.e. how do we refer to the output of a derivation, which is itself an output of a derivation?) For that we need to generalize the definition of deriving path, replacing the store path used to refer to the derivation with a nested deriving path:

 type OutputPath = {
-  drvPath: StorePath;
+  drvPath: DerivingPath;
   output: OutputName;
 };

Now, the drvPath field of OutputPath is itself a DerivingPath instead of a StorePath.

With that change, here is updated definition:

type OutputName = String;

type ConstantPath = {
  path: StorePath;
};

type OutputPath = {
  drvPath: DerivingPath;
  output: OutputName;
};

type DerivingPath = ConstantPath | OutputPath;

Under this extended model, DerivingPaths are thus inductively built up from a root ConstantPath, wrapped with zero or more outer OutputPaths.

Encoding

The encoding is adjusted in the natural way, encoding the drv field recursively using the same deriving path encoding. The result of this is that it is possible to have a chain of ^<output-name> at the end of the final string, as opposed to just a single one.

Example

/nix/store/lxrn8v5aamkikg6agxwdqd1jz7746wz4-firefox-98.0.2.drv^foo.drv^bar.drv^out
|----------------------------------------------------------------------------| |-|
inner deriving path (usual encoding)                                           output name
|--------------------------------------------------------------------| |-----|
even more inner deriving path (usual encoding)                         output name
|------------------------------------------------------------| |-----|
innermost constant store path (usual encoding)                 output name

Derivation Outputs and Types of Derivations

As stated on the main pages on derivations, a derivation produces [store objects], which are known as the outputs of the derivation. Indeed, the entire point of derivations is to produce these outputs, and to reliably and reproducably produce these derivations each time the derivation is run.

One of the parts of a derivation is its outputs specification, which specifies certain information about the outputs the derivation produces when run. The outputs specification is a map, from names to specifications for individual outputs.

Output Names

Output names can be any string which is also a valid [store path] name. The name mapped to each output specification is not actually the name of the output. In the general case, the output store object has name derivationName + "-" + outputSpecName, not any other metadata about it. However, an output spec named "out" describes and output store object whose name is just the derivation name.

Example

A derivation is named hello, and has two outputs, out, and dev

  • The derivation's path will be: /nix/store/<hash>-hello.drv.

  • The store path of out will be: /nix/store/<hash>-hello.

  • The store path of dev will be: /nix/store/<hash>-hello-dev.

The outputs are the derivations are the [store objects][store object] it is obligated to produce.

Note

The formal terminology here is somewhat at adds with everyday communication in the Nix community today. "output" in casual usage tends to refer to either to the actual output store object, or the notional output spec, depending on context.

For example "hello's dev output" means the store object referred to by the store path /nix/store/<hash>-hello-dev. It is unusual to call this the "hello-dev output", even though hello-dev is the actual name of that store object.

Types of output addressing

The main information contained in an output specification is how the derivation output is addressed. In particular, the specification decides:

Types of derivations

The sections on each type of derivation output addressing ended up discussing other attributes of the derivation besides its outputs, such as purity, scheduling, determinism, etc. This is no concidence; for the type of a derivation is in fact one-for-one with the type of its outputs:

  • A derivation that produces xyz-addressed outputs is an xyz-addressing derivations.

The rules for this are fairly concise:

  • All the outputs must be of the same type / use the same addressing

    • The derivation must have at least one output

    • Additionally, if the outputs are fixed content-addressed, there must be exactly one output, whose specification is mapped from the name out. (The name out is special, according to the rules described above. Having only one output and calling its specification out means the single output is effectively anonymous; the store path just has the derivation name.)

      (This is an arbitrary restriction that could be lifted.)

  • The output is either fixed or floating, indicating whether the its store path is known prior to building it.

    • With fixed content-addressing it is fixed.

      A fixed content-addressing derivation is also called a fixed-output derivation, since that is the only currently-implemented form of fixed-output addressing

    • With floating content-addressing or input-addressing it is floating.

    Thus, historically with Nix, with no experimental features enabled, all outputs are fixed.

  • The derivation may be pure or impure, indicating what read access to the outside world the builder has.

    • An input-addressing derivation must be pure.

      If it is impure, we would have a large problem, because an input-addressed derivation always produces outputs with the same paths.

    • A content-addressing derivation may be pure or impure

    • If it is impure, it may be be fixed (typical), or it may be floating if the additional impure-derivations experimental feature is enabled.

    • If it is pure, it must be floating.

    • Pure, fixed content-addressing derivations are not suppported

      There is no use for this forth combination. The sole purpose of an output's store path being fixed is to support the derivation being impure.

Content-addressing derivation outputs

The content-addressing of an output only depends on that store object itself, not any other information external (such has how it was made, when it was made, etc.). As a consequence, a store object will be content-addressed the same way regardless of whether it was manually inserted into the store, outputted by some derivation, or outputted by a some other derivation.

The output spec for a content-addressed output must contains the following field:

  • method: how the data of the store object is digested into a content address

The possible choices of method are described in the section on content-addressing store objects. Given the method, the output's name (computed from the derivation name and output spec mapping as described above), and the data of the store object, the output's store path will be computed as described in that section.

Fixed-output content-addressing

In this case the content address of the fixed in advanced by the derivation itself. In other words, when the derivation has finished building, and the provisional output' content-address is computed as part of the process to turn it into a bona fide store object, the calculated content address must much that given in the derivation, or the build of that derivation will be deemed a failure.

The output spec for an output with a fixed content addresses additionally contains:

  • hash, the hash expected from digesting the store object's file system objects. This hash may be of a freely-chosen hash algorithm (that Nix supports)

Design note

In principle, the output spec could also specify the references the store object should have, since the references and file system objects are equally parts of a content-addressed store object proper that contribute to its content-addressed. However, at this time, the references are not not done because all fixed content-addressed outputs are required to have no references (including no self-reference).

Also in principle, rather than specifying the references and file system object data with separate hashes, a single hash that constraints both could be used. This could be done with the final store path's digest, or better yet, the hash that will become the store path's digest before it is truncated.

These possible future extensions are included to elucidate the core property of fixed-output content addressing --- that all parts of the output must be cryptographically fixed with one or more hashes --- separate from the particulars of the currently-supported store object content-addressing schemes.

Design rationale

What is the purpose of fixing an output's content address in advanced? In abstract terms, the answer is carefully controlled impurity. Unlike a regular derivation, the builder executable of a derivation that produced fixed outputs has access to the network. The outputs' guaranteed content-addresses are supposed to mitigate the risk of the builder being given these capabilities; regardless of what the builder does during the build, it cannot influence downstream builds in unanticipated ways because all information it passed downstream flows through the outputs whose content-addresses are fixed.

In concrete terms, the purpose of this feature is fetching fixed input data like source code from the network. For example, consider a family of "fetch URL" derivations. These derivations download files from given URL. To ensure that the downloaded file has not been modified, each derivation must also specify a cryptographic hash of the file. For example,

{
  "outputs: {
    "out": {
      "method": "nar",
      "hashAlgo": "sha256",
      "hash: "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465",
    },
  },
  "env": {
    "url": "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz"
    // ...
  },
  // ...
}

It sometimes happens that the URL of the file changes, e.g., because servers are reorganised or no longer available. In these cases, we then must update the call to fetchurl, e.g.,

   "env": {
-    "url": "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz"
+    "url": "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz"
     // ...
   },

If a fetchurl derivation's outputs were input-addressed, the output paths of the derivation and of all derivations depending on it would change. For instance, if we were to change the URL of the Glibc source distribution in Nixpkgs (a package on which almost all other packages depend on Linux) massive rebuilds would be needed. This is unfortunate for a change which we know cannot have a real effect as it propagates upwards through the dependency graph.

For content-addressed outputs (fixed or floating), on the other hand, the outputs' store path only depends on the derivation's name, data, and the method of the outputs' specs. The rest of the derivation is ignored for the purpose of computing the output path.

History Note

Fixed content-addressing is especially important both today and historically as the only form of content-addressing that is stabilized. This is why the rationale above contrasts it with input addressing.

(Floating) Content-Addressing

Warning This is part of an experimental feature.

To use this type of output addressing, you must enable the ca-derivations experimental feature. For example, in nix.conf you could add:

extra-experimental-features = ca-derivations

With this experimemental feature enabled, derivation outputs can also be content-addressed without fixing in the output spec what the outputs' content address must be.

Purity

Because the derivation output is not fixed (just like with input addressing), the builder is not given any impure capabilities [^purity].

Configuration note

Strictly speaking, the extent to which sandboxing and deprivilaging is possible varies with the environment Nix is running in. Nix's configuration settings indicate what level of sandboxing is required or enabled. Builds of derivations will fail if they request an absense of sandboxing which is not allowed. Builds of derivations will also fail if the level of sandboxing specified in the configure exceeds what is possible in teh given environment.

(The "environment", in this case, consists of attributes such as the Operating System Nix runs atop, along with the operating-system-specific privilages that Nix has been granted. Because of how conventional operating systems like macos, Linux, etc. work, granting builders fewer privilages may ironically require that Nix be run with more privilages.)

That said, derivations producing floating content-addressed outputs may declare their builders as impure (like the builders of derivations producing producing fixed outputs). This is provisionally supported as part of the impure-derivations experimental feature.

Compatibility negotiation

Any derivation producing a floating content-addresssed output implicitly requires the ca-derivations system feature. This prevents scheduling the building of the derivation on a machine without the experimental feature enabled. Even once the experimental feature is stabilized, this is still useful in order to be allow using remote builder running odler versions of Nix, or alternative implementations that do not support floating content addressing.

Determinism

In the earlier discussion of how self-references are handled when content-addressing store objects, it was pointed out that methods of producing store objects ought to be deterministic regardless of the choice of provisional store path. For store objects produced by manually inserting into the store to create a store object, the "method of production" is an informally concept --- formally, Nix has no idea where the store object came from, and content-addressing is crucial in order to ensure that the derivation is intrinsically tamper-proof. But for store objects produced by derivation, the "method is quite formal" --- the whole point of derivations is to be a formal notion of building, after all. In this case, we can elevate this informal property to a formal one.

A determinstic content-addressing derivation should produce outputs with the same content addresses:

  1. Every time the builder is run

This is because either the builder is completely sandboxed, or because all any remaining impurities that leak inside the build sandbox are ignored by the builder and do not influence its behavior.

  1. Regardless of the choice of any provisional outputs paths

Provisional store paths must be chosen for any output that has a self-reference. The choice of provisional store path can be thought of as an impurity, since it is an arbitrary choice.

If provisional outputs paths are deterministically chosen, we are in the first branch of part (1). The builder the data it produces based on it in arbitrary ways, but this gets us closer to to input addressing. Deterministically choosing the provisional path may be considered "complete sandboxing" by removing an impurity, but this is unsatisfactory

If provisional outputs paths are randomly chosen, we are in the second branch of part (1). The builder must not let the random input affect the final outputs it produces, and multiple builds may be performed and the compared in order to ensure that this is in fact the case.

Floating versus Fixed

While the distinction between content- and input-addressing is one of mechanism, the distinction between fixed and floating content addressing is more one of policy. A fixed output that passes its content address check is just like a floating output. It is only in the potential for that check to fail that they are different.

Design Note

In a future world where floating content-addressing is also stable, we in principle no longer need separate fixed content-addressing. Instead, we could always use floating content-addressing, and separately assert the precise value content address of a given store object to be used as an input (of another derivation). A stand-alone assertion object of this sort is not yet implemented, but its possible creation is tracked in Issue #11955.

In the current version of Nix, fixed outputs which fail their hash check are still registered as valid store objects, just not registered as outputs of the derivation which produced them. This is an optimization that means if the wrong output hash is specified in a derivation, and then the derivation is recreated with the right output hash, derivation does not need to be rebuilt --- avoiding downloading potentially large amounts of data twice. This optimisation prefigures the design above: If the output hash assertion was removed outside the derivation itself, Nix could additionally not only register that outputted store object like today, but could also make note that derivation did in fact successfully download some data. For example, for the "fetch URL" example above, making such a note is tantamount to recording what data is available at the time of download at the given URL. It would only be when Nix subsequently tries to build something with that (refining our example) downloaded source code that Nix would be forced to check the output hash assertion, preventing it from e.g. building compromised malware.

Recapping, Nix would

  1. successfully download data
  2. insert that data into the store
  3. associate (presumably with some sort of expiration policy) the downloaded data with the derivation that downloaded it

But only use the downloaded store object in subsequent derivations that depended upon the assertion if the assertion passed.

This possible future extension is included to illustrate this distinction:

Input-addressing derivation outputs

"Input addressing" means the address the store object by the way it was made rather than what it is. That is to say, an input-addressed output's store path is a function not of the output itself, but of the derivation that produced it. Even if two store paths have the same contents, if they are produced in different ways, and one is input-addressed, then they will have different store paths, and thus guaranteed to not be the same store object.

Building

Normalizing derivation inputs

  • Each input must be realised prior to building the derivation in question.
  • Once this is done, the derivation is normalized, replacing each input deriving path with its store path, which we now know from realising the input.

Builder Execution

The builder is executed as follows:

  • A temporary directory is created under the directory specified by TMPDIR (default /tmp) where the build will take place. The current directory is changed to this directory.

  • The environment is cleared and set to the derivation attributes, as specified above.

  • In addition, the following variables are set:

    • NIX_BUILD_TOP contains the path of the temporary directory for this build.

    • Also, TMPDIR, TEMPDIR, TMP, TEMP are set to point to the temporary directory. This is to prevent the builder from accidentally writing temporary files anywhere else. Doing so might cause interference by other processes.

    • PATH is set to /path-not-set to prevent shells from initialising it to their built-in default value.

    • HOME is set to /homeless-shelter to prevent programs from using /etc/passwd or the like to find the user's home directory, which could cause impurity. Usually, when HOME is set, it is used as the location of the home directory, even if it points to a non-existent path.

    • NIX_STORE is set to the path of the top-level Nix store directory (typically, /nix/store).

    • NIX_ATTRS_JSON_FILE & NIX_ATTRS_SH_FILE if __structuredAttrs is set to true for the derivation. A detailed explanation of this behavior can be found in the section about structured attrs.

    • For each output declared in outputs, the corresponding environment variable is set to point to the intended path in the Nix store for that output. Each output path is a concatenation of the cryptographic hash of all build inputs, the name attribute and the output name. (The output name is omitted if it’s out.)

  • If an output path already exists, it is removed. Also, locks are acquired to prevent multiple Nix instances from performing the same build at the same time.

  • A log of the combined standard output and error is written to /nix/var/log/nix.

  • The builder is executed with the arguments specified by the attribute args. If it exits with exit code 0, it is considered to have succeeded.

  • The temporary directory is removed (unless the -K option was specified).

Processing outputs

If the builder exited successfully, the following steps happen in order to turn the output directories left behind by the builder into proper store objects:

  • Normalize the file permissions

    Nix sets the last-modified timestamp on all files in the build result to 1 (00:00:01 1/1/1970 UTC), sets the group to the default group, and sets the mode of the file to 0444 or 0555 (i.e., read-only, with execute permission enabled if the file was originally executable). Any possible setuid and setgid bits are cleared.

    Note

    Setuid and setgid programs are not currently supported by Nix. This is because the Nix archives used in deployment have no concept of ownership information, and because it makes the build result dependent on the user performing the build.

  • Calculate the references

    Nix scans each output path for references to input paths by looking for the hash parts of the input paths. Since these are potential runtime dependencies, Nix registers them as dependencies of the output paths.

    Nix also scans for references to other outputs' paths in the same way, because outputs are allowed to refer to each other. If the outputs' references to each other form a cycle, this is an error, because the references of store objects much be acyclic.

Nix supports different types of stores:

Store URL format

Stores are specified using a URL-like syntax. For example, the command

# nix path-info --store https://cache.nixos.org/ --json \
  /nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1

fetches information about a store path in the HTTP binary cache located at https://cache.nixos.org/, which is a type of store.

Store URLs can specify store settings using URL query strings, i.e. by appending ?name1=value1&name2=value2&... to the URL. For instance,

--store ssh://machine.example.org?ssh-key=/path/to/my/key

tells Nix to access the store on a remote machine via the SSH protocol, using /path/to/my/key as the SSH private key. The supported settings for each store type are documented below.

The special store URL auto causes Nix to automatically select a store as follows:

Dummy Store

Store URL format: dummy://

This store type represents a store that contains no store paths and cannot be written to. It's useful when you want to use the Nix evaluator when no actual Nix store exists, e.g.

# nix eval --store dummy:// --expr '1 + 2'

Settings

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Experimental Local Overlay Store

Warning

This store is part of an experimental feature.

To use this store, make sure the local-overlay-store experimental feature is enabled. For example, include the following in nix.conf:

extra-experimental-features = local-overlay-store

Store URL format: local-overlay

This store type is a variation of the [local store] designed to leverage Linux's Overlay Filesystem (OverlayFS for short). Just as OverlayFS combines a lower and upper filesystem by treating the upper one as a patch against the lower, the local overlay store combines a lower store with an upper almost-[local store]. ("almost" because while the upper filesystems for OverlayFS is valid on its own, the upper almost-store is not a valid local store on its own because some references will dangle.) To use this store, you will first need to configure an OverlayFS mountpoint appropriately as Nix will not do this for you (though it will verify the mountpoint is configured correctly).

Conceptual parts of a local overlay store

This is a more abstract/conceptual description of the parts of a layered store, an authoritative reference. For more "practical" instructions, see the worked-out example in the next subsection.

The parts of a local overlay store are as follows:

  • Lower store:

    Specified with the lower-store setting.

    This is any store implementation that includes a store directory as part of the native operating system filesystem. For example, this could be a [local store], [local daemon store], or even another local overlay store.

    The local overlay store never tries to modify the lower store in any way. Something else could modify the lower store, but there are restrictions on this Nix itself requires that this store only grow, and not change in other ways. For example, new store objects can be added, but deleting or modifying store objects is not allowed in general, because that will confuse and corrupt any local overlay store using those objects. (In addition, the underlying filesystem overlay mechanism may impose additional restrictions, see below.)

    The lower store must not change while it is mounted as part of an overlay store. To ensure it does not, you might want to mount the store directory read-only (which then requires the [read-only] parameter to be set to true).

    • Lower store directory:

      Specified with lower-store.real setting.

      This is the directory used/exposed by the lower store.

      As specified above, Nix requires the local store can only grow not change in other ways. Linux's OverlayFS in addition imposes the further requirement that this directory cannot change at all. That means that, while any local overlay store exists that is using this store as a lower store, this directory must not change.

    • Lower metadata source:

      Not directly specified. A consequence of the lower-store setting, depending on the type of lower store chosen.

      This is abstract, just some way to read the metadata of lower store store objects. For example it could be a SQLite database (for the [local store]), or a socket connection (for the [local daemon store]).

      This need not be writable. As stated above a local overlay store never tries to modify its lower store. The lower store's metadata is considered part of the lower store, just as the store's file system objects that appear in the store directory are.

  • Upper almost-store:

    Not directly specified. Instead the constituent parts are independently specified as described below.

    This is almost but not quite just a [local store]. That is because taken in isolation, not as part of a local overlay store, by itself, it would appear corrupted. But combined with everything else as part of an overlay local store, it is valid.

    • Upper layer directory:

      Specified with upper-layer setting.

      This contains additional store objects (or, strictly speaking, their file system objects that the local overlay store will extend the lower store with).

    • Upper store directory:

      Specified with the real setting. This the same as the base local store setting, and can also be indirectly specified with the root setting.

      This contains all the store objects from each of the two directories.

      The lower store directory and upper layer directory are combined via OverlayFS to create this directory. Nix doesn't do this itself, because it typically wouldn't have the permissions to do so, so it is the responsibility of the user to set this up first. Nix can, however, optionally check that the OverlayFS mount settings appear as expected, matching Nix's own settings.

    • Upper SQLite database:

      Not directly specified. The location of the database instead depends on the state setting. It is always ${state}/db.

      This contains the metadata of all of the upper layer store objects (everything beyond their file system objects), and also duplicate copies of some lower layer store object's metadta. The duplication is so the metadata for the closure of upper layer store objects can be found entirely within the upper layer. (This allows us to use the same SQL Schema as the [local store]'s SQLite database, as foreign keys in that schema enforce closure metadata to be self-contained in this way.)

Example filesystem layout

Here is a worked out example of usage, following the concepts in the previous section.

Say we have the following paths:

  • /mnt/example/merged-store/nix/store

  • /mnt/example/store-a/nix/store

  • /mnt/example/store-b

Then the following store URI can be used to access a local-overlay store at /mnt/example/merged-store:

local-overlay://?root=/mnt/example/merged-store&lower-store=/mnt/example/store-a&upper-layer=/mnt/example/store-b

The lower store directory is located at /mnt/example/store-a/nix/store, while the upper layer is at /mnt/example/store-b.

Before accessing the overlay store you will need to ensure the OverlayFS mount is set up correctly:

mount -t overlay overlay \
  -o lowerdir="/mnt/example/store-a/nix/store" \
  -o upperdir="/mnt/example/store-b" \
  -o workdir="/mnt/example/workdir" \
  "/mnt/example/merged-store/nix/store"

Note that OverlayFS requires /mnt/example/workdir to be on the same volume as the upperdir.

By default, Nix will check that the mountpoint as been set up correctly and fail with an error if it has not. You can override this behaviour by passing check-mount=false if you need to.

Settings

  • check-mount

    Check that the overlay filesystem is correctly mounted.

    Nix does not manage the overlayfs mount point itself, but the correct functioning of the overlay store does depend on this mount point being set up correctly. Rather than just assume this is the case, check that the lowerdir and upperdir options are what we expect them to be. This check is on by default, but can be disabled if needed.

    Default: true

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • lower-store

    Store URL for the lower store. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Must be a store with a store dir on the file system. Must be used as OverlayFS lower layer for this store's store dir.

    Default: empty

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • read-only

    Allow this store to be opened when its database is on a read-only filesystem.

    Normally Nix will attempt to open the store database in read-write mode, even for querying (when write access is not needed), causing it to fail if the database is on a read-only filesystem.

    Enable read-only mode to disable locking and open the SQLite database with the immutable parameter set.

    Warning Do not use this unless the filesystem is read-only.

    Using it when the filesystem is writable can cause incorrect query results or corruption errors if the database is changed by another process. While the filesystem the database resides on might appear to be read-only, consider whether another user or system might have write access to it.

    Default: false

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • remount-hook

    Script or other executable to run when overlay filesystem needs remounting.

    This is occasionally necessary when deleting a store path that exists in both upper and lower layers. In such a situation, bypassing OverlayFS and deleting the path in the upper layer directly is the only way to perform the deletion without creating a "whiteout". However this causes the OverlayFS kernel data structures to get out-of-sync, and can lead to 'stale file handle' errors; remounting solves the problem.

    The store directory is passed as an argument to the invoked executable.

    Default: empty

  • require-sigs

    Whether store paths copied into this store should have a trusted signature.

    Default: true

  • root

    Directory prefixed to all other paths.

    Default: ``

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • upper-layer

    Directory containing the OverlayFS upper layer for this store's store dir.

    Default: empty

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Experimental SSH Store

Store URL format: ssh-ng://[username@]hostname

Experimental store type that allows full access to a Nix store on a remote machine.

Settings

  • base64-ssh-public-host-key

    The public host key of the remote machine.

    Default: empty

  • compress

    Whether to enable SSH compression.

    Default: false

  • max-connection-age

    Maximum age of a connection before it is closed.

    Default: 4294967295

  • max-connections

    Maximum number of concurrent connections to the Nix daemon.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • remote-program

    Path to the nix-daemon executable on the remote machine.

    Default: nix-daemon

  • remote-store

    Store URL to be used on the remote machine. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Default: empty

  • ssh-key

    Path to the SSH private key used to authenticate to the remote machine.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Experimental SSH Store with filesystem mounted

Warning

This store is part of an experimental feature.

To use this store, make sure the mounted-ssh-store experimental feature is enabled. For example, include the following in nix.conf:

extra-experimental-features = mounted-ssh-store

Store URL format: mounted-ssh-ng://[username@]hostname

Experimental store type that allows full access to a Nix store on a remote machine, and additionally requires that store be mounted in the local file system.

The mounting of that store is not managed by Nix, and must by managed manually. It could be accomplished with SSHFS or NFS, for example.

The local file system is used to optimize certain operations. For example, rather than serializing Nix archives and sending over the Nix channel, we can directly access the file system data via the mount-point.

The local file system is also used to make certain operations possible that wouldn't otherwise be. For example, persistent GC roots can be created if they reside on the same file system as the remote store: the remote side will create the symlinks necessary to avoid race conditions.

Settings

  • base64-ssh-public-host-key

    The public host key of the remote machine.

    Default: empty

  • compress

    Whether to enable SSH compression.

    Default: false

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • max-connection-age

    Maximum age of a connection before it is closed.

    Default: 4294967295

  • max-connections

    Maximum number of concurrent connections to the Nix daemon.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • remote-program

    Path to the nix-daemon executable on the remote machine.

    Default: nix-daemon

  • remote-store

    Store URL to be used on the remote machine. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Default: empty

  • root

    Directory prefixed to all other paths.

    Default: ``

  • ssh-key

    Path to the SSH private key used to authenticate to the remote machine.

    Default: empty

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

HTTP Binary Cache Store

Store URL format: http://..., https://...

This store allows a binary cache to be accessed via the HTTP protocol.

Settings

  • compression

    NAR compression method (xz, bzip2, gzip, zstd, or none).

    Default: xz

  • compression-level

    The preset level to be used when compressing NARs. The meaning and accepted values depend on the compression method selected. -1 specifies that the default compression level should be used.

    Default: -1

  • index-debug-info

    Whether to index DWARF debug info files by build ID. This allows dwarffs to fetch debug info on demand

    Default: false

  • local-nar-cache

    Path to a local cache of NARs fetched from this binary cache, used by commands such as nix store cat.

    Default: empty

  • parallel-compression

    Enable multi-threaded compression of NARs. This is currently only available for xz and zstd.

    Default: false

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • secret-key

    Path to the secret key used to sign the binary cache.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

  • write-nar-listing

    Whether to write a JSON file that lists the files in each NAR.

    Default: false

Local Binary Cache Store

Store URL format: file://path

This store allows reading and writing a binary cache stored in path in the local filesystem. If path does not exist, it will be created.

For example, the following builds or downloads nixpkgs#hello into the local store and then copies it to the binary cache in /tmp/binary-cache:

# nix copy --to file:///tmp/binary-cache nixpkgs#hello

Settings

  • compression

    NAR compression method (xz, bzip2, gzip, zstd, or none).

    Default: xz

  • compression-level

    The preset level to be used when compressing NARs. The meaning and accepted values depend on the compression method selected. -1 specifies that the default compression level should be used.

    Default: -1

  • index-debug-info

    Whether to index DWARF debug info files by build ID. This allows dwarffs to fetch debug info on demand

    Default: false

  • local-nar-cache

    Path to a local cache of NARs fetched from this binary cache, used by commands such as nix store cat.

    Default: empty

  • parallel-compression

    Enable multi-threaded compression of NARs. This is currently only available for xz and zstd.

    Default: false

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • secret-key

    Path to the secret key used to sign the binary cache.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

  • write-nar-listing

    Whether to write a JSON file that lists the files in each NAR.

    Default: false

Local Daemon Store

Store URL format: daemon, unix://path

This store type accesses a Nix store by talking to a Nix daemon listening on the Unix domain socket path. The store pseudo-URL daemon is equivalent to unix:///nix/var/nix/daemon-socket/socket.

Settings

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • max-connection-age

    Maximum age of a connection before it is closed.

    Default: 4294967295

  • max-connections

    Maximum number of concurrent connections to the Nix daemon.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • root

    Directory prefixed to all other paths.

    Default: ``

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Local Store

Store URL format: local, root

This store type accesses a Nix store in the local filesystem directly (i.e. not via the Nix daemon). root is an absolute path that is prefixed to other directories such as the Nix store directory. The store pseudo-URL local denotes a store that uses / as its root directory.

A store that uses a root other than / is called a chroot store. With such stores, the store directory is "logically" still /nix/store, so programs stored in them can only be built and executed by chroot-ing into root. Chroot stores only support building and running on Linux when mount namespaces and user namespaces are enabled.

For example, the following uses /tmp/root as the chroot environment to build or download nixpkgs#hello and then execute it:

# nix run --store /tmp/root nixpkgs#hello
Hello, world!

Here, the "physical" store location is /tmp/root/nix/store, and Nix's store metadata is in /tmp/root/nix/var/nix/db.

It is also possible, but not recommended, to change the "logical" location of the Nix store from its default of /nix/store. This makes it impossible to use default substituters such as https://cache.nixos.org/, and thus you may have to build everything locally. Here is an example:

# nix build --store 'local?store=/tmp/my-nix/store&state=/tmp/my-nix/state&log=/tmp/my-nix/log' nixpkgs#hello

Settings

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • read-only

    Allow this store to be opened when its database is on a read-only filesystem.

    Normally Nix will attempt to open the store database in read-write mode, even for querying (when write access is not needed), causing it to fail if the database is on a read-only filesystem.

    Enable read-only mode to disable locking and open the SQLite database with the immutable parameter set.

    Warning Do not use this unless the filesystem is read-only.

    Using it when the filesystem is writable can cause incorrect query results or corruption errors if the database is changed by another process. While the filesystem the database resides on might appear to be read-only, consider whether another user or system might have write access to it.

    Default: false

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • require-sigs

    Whether store paths copied into this store should have a trusted signature.

    Default: true

  • root

    Directory prefixed to all other paths.

    Default: ``

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

S3 Binary Cache Store

Store URL format: s3://bucket-name

This store allows reading and writing a binary cache stored in an AWS S3 (or S3-compatible service) bucket. This store shares many idioms with the HTTP Binary Cache Store.

For AWS S3, the binary cache URL for a bucket named example-nix-cache will be exactly s3://example-nix-cache. For S3 compatible binary caches, consult that cache's documentation.

Anonymous reads to your S3-compatible binary cache

If your binary cache is publicly accessible and does not require authentication, it is simplest to use the [HTTP Binary Cache Store] rather than S3 Binary Cache Store with https://example-nix-cache.s3.amazonaws.com instead of s3://example-nix-cache.

Your bucket will need a bucket policy like the following to be accessible:

{
    "Id": "DirectReads",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowDirectReads",
            "Action": [
                "s3:GetObject",
                "s3:GetBucketLocation"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::example-nix-cache",
                "arn:aws:s3:::example-nix-cache/*"
            ],
            "Principal": "*"
        }
    ]
}

Authentication

Nix will use the default credential provider chain for authenticating requests to Amazon S3.

Note that this means Nix will read environment variables and files with different idioms than with Nix's own settings, as implemented by the AWS SDK. Consult the documentation linked above for further details.

Authenticated reads to your S3 binary cache

Your bucket will need a bucket policy allowing the desired users to perform the s3:GetObject and s3:GetBucketLocation action on all objects in the bucket. The anonymous policy given above can be updated to have a restricted Principal to support this.

Authenticated writes to your S3-compatible binary cache

Your account will need an IAM policy to support uploading to the bucket:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "UploadToCache",
      "Effect": "Allow",
      "Action": [
        "s3:AbortMultipartUpload",
        "s3:GetBucketLocation",
        "s3:GetObject",
        "s3:ListBucket",
        "s3:ListBucketMultipartUploads",
        "s3:ListMultipartUploadParts",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::example-nix-cache",
        "arn:aws:s3:::example-nix-cache/*"
      ]
    }
  ]
}

Examples

With bucket policies and authentication set up as described above, uploading works via nix copy (experimental).

  • To upload with a specific credential profile for Amazon S3:

    $ nix copy nixpkgs.hello \
      --to 's3://example-nix-cache?profile=cache-upload&region=eu-west-2'
    
  • To upload to an S3-compatible binary cache:

    $ nix copy nixpkgs.hello --to \
      's3://example-nix-cache?profile=cache-upload&scheme=https&endpoint=minio.example.com'
    

Settings

  • buffer-size

    Size (in bytes) of each part in multi-part uploads.

    Default: 5242880

  • compression

    NAR compression method (xz, bzip2, gzip, zstd, or none).

    Default: xz

  • compression-level

    The preset level to be used when compressing NARs. The meaning and accepted values depend on the compression method selected. -1 specifies that the default compression level should be used.

    Default: -1

  • endpoint

    The URL of the endpoint of an S3-compatible service such as MinIO. Do not specify this setting if you're using Amazon S3.

    Note

    This endpoint must support HTTPS and will use path-based addressing instead of virtual host based addressing.

    Default: empty

  • index-debug-info

    Whether to index DWARF debug info files by build ID. This allows dwarffs to fetch debug info on demand

    Default: false

  • local-nar-cache

    Path to a local cache of NARs fetched from this binary cache, used by commands such as nix store cat.

    Default: empty

  • log-compression

    Compression method for log/* files. It is recommended to use a compression method supported by most web browsers (e.g. brotli).

    Default: empty

  • ls-compression

    Compression method for .ls files.

    Default: empty

  • multipart-upload

    Whether to use multi-part uploads.

    Default: false

  • narinfo-compression

    Compression method for .narinfo files.

    Default: empty

  • parallel-compression

    Enable multi-threaded compression of NARs. This is currently only available for xz and zstd.

    Default: false

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • profile

    The name of the AWS configuration profile to use. By default Nix will use the default profile.

    Default: empty

  • region

    The region of the S3 bucket. If your bucket is not in us–east-1, you should always explicitly specify the region parameter.

    Default: us-east-1

  • scheme

    The scheme used for S3 requests, https (default) or http. This option allows you to disable HTTPS for binary caches which don't support it.

    Note

    HTTPS should be used if the cache might contain sensitive information.

    Default: empty

  • secret-key

    Path to the secret key used to sign the binary cache.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

  • write-nar-listing

    Whether to write a JSON file that lists the files in each NAR.

    Default: false

SSH Store

Store URL format: ssh://[username@]hostname

This store type allows limited access to a remote store on another machine via SSH.

Settings

  • base64-ssh-public-host-key

    The public host key of the remote machine.

    Default: empty

  • compress

    Whether to enable SSH compression.

    Default: false

  • max-connections

    Maximum number of concurrent SSH connections.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • remote-program

    Path to the nix-store executable on the remote machine.

    Default: nix-store

  • remote-store

    Store URL to be used on the remote machine. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Default: empty

  • ssh-key

    Path to the SSH private key used to authenticate to the remote machine.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Nix Language

The Nix language is designed for conveniently creating and composing derivations – precise descriptions of how contents of existing files are used to derive new files.

Tip

These pages are written as a reference. If you are learning Nix, nix.dev has a good introduction to the Nix language.

The language is:

  • domain-specific

    It comes with built-in functions to integrate with the Nix store, which manages files and performs the derivations declared in the Nix language.

  • declarative

    There is no notion of executing sequential steps. Dependencies between operations are established only through data.

  • pure

    Values cannot change during computation. Functions always produce the same output if their input does not change.

  • functional

    Functions are like any other value. Functions can be assigned to names, taken as arguments, or returned by functions.

  • lazy

    Values are only computed when they are needed.

  • dynamically typed

    Type errors are only detected when expressions are evaluated.

Overview

This is an incomplete overview of language features, by example.

Example Description

Basic values (primitives)

"hello world"

A string

''
  multi
   line
    string
''

A multi-line string. Strips common prefixed whitespace. Evaluates to "multi\n line\n  string".

# Explanation

A comment.

"hello ${ { a = "world"; }.a }"

"1 2 ${toString 3}"

"${pkgs.bash}/bin/sh"

String interpolation (expands to "hello world", "1 2 3", "/nix/store/<hash>-bash-<version>/bin/sh")

true, false

Booleans

null

Null value

123

An integer

3.141

A floating point number

/etc

An absolute path

./foo.png

A path relative to the file containing this Nix expression

~/.config

A home path. Evaluates to the "<user's home directory>/.config".

<nixpkgs>

A lookup path for Nix files. Value determined by $NIX_PATH environment variable.

Compound values

{ x = 1; y = 2; }

An attribute set with attributes named x and y

{ foo.bar = 1; }

A nested set, equivalent to { foo = { bar = 1; }; }

rec { x = "foo"; y = x + "bar"; }

A recursive set, equivalent to { x = "foo"; y = "foobar"; }.

[ "foo" "bar" "baz" ]

[ 1 2 3 ]

[ (f 1) { a = 1; b = 2; } [ "c" ] ]

Lists with three elements.

Operators

"foo" + "bar"

String concatenation

1 + 2

Integer addition

"foo" == "f" + "oo"

Equality test (evaluates to true)

"foo" != "bar"

Inequality test (evaluates to true)

!true

Boolean negation

{ x = 1; y = 2; }.x

Attribute selection (evaluates to 1)

{ x = 1; y = 2; }.z or 3

Attribute selection with default (evaluates to 3)

{ x = 1; y = 2; } // { z = 3; }

Merge two sets (attributes in the right-hand set taking precedence)

Control structures

if 1 + 1 == 2 then "yes!" else "no!"

Conditional expression.

assert 1 + 1 == 2; "yes!"

Assertion check (evaluates to "yes!").

let x = "foo"; y = "bar"; in x + y

Variable definition. See let-expressions.

with builtins; head [ 1 2 3 ]

Add all attributes from the given set to the scope (evaluates to 1).

See with-expressions for details and shadowing caveats.

inherit pkgs src;

Adds the variables to the current scope (attribute set or let binding). Desugars to pkgs = pkgs; src = src;. See Inheriting attributes.

inherit (pkgs) lib stdenv;

Adds the attributes, from the attribute set in parentheses, to the current scope (attribute set or let binding). Desugars to lib = pkgs.lib; stdenv = pkgs.stdenv;. See Inheriting attributes.

Functions (lambdas)

x: x + 1

A function that expects an integer and returns it increased by 1.

x: y: x + y

Curried function, equivalent to x: (y: x + y). Can be used like a function that takes two arguments and returns their sum.

(x: x + 1) 100

A function call (evaluates to 101)

let inc = x: x + 1; in inc (inc (inc 100))

A function bound to a variable and subsequently called by name (evaluates to 103)

{ x, y }: x + y

A function that expects a set with required attributes x and y and concatenates them

{ x, y ? "bar" }: x + y

A function that expects a set with required attribute x and optional y, using "bar" as default value for y

{ x, y, ... }: x + y

A function that expects a set with required attributes x and y and ignores any other attributes

{ x, y } @ args: x + y

args @ { x, y }: x + y

A function that expects a set with required attributes x and y, and binds the whole set to args

Built-in functions

import ./foo.nix

Load and return Nix expression in given file. See import.

map (x: x + x) [ 1 2 3 ]

Apply a function to every element of a list (evaluates to [ 2 4 6 ]). See map.

Data Types

Every value in the Nix language has one of the following types:

Primitives

Integer

An integer in the Nix language is a signed 64-bit integer.

Non-negative integers can be expressed as integer literals. Negative integers are created with the arithmetic negation operator. The function builtins.isInt can be used to determine if a value is an integer.

Float

A float in the Nix language is a 64-bit IEEE 754 floating-point number.

Most non-negative floats can be expressed as float literals. Negative floats are created with the arithmetic negation operator. The function builtins.isFloat can be used to determine if a value is a float.

Boolean

A boolean in the Nix language is one of true or false.

These values are available as attributes of builtins as builtins.true and builtins.false. The function builtins.isBool can be used to determine if a value is a boolean.

String

A string in the Nix language is an immutable, finite-length sequence of bytes, along with a string context. Nix does not assume or support working natively with character encodings.

String values without string context can be expressed as string literals. The function builtins.isString can be used to determine if a value is a string.

Path

A path in the Nix language is an immutable, finite-length sequence of bytes starting with /, representing a POSIX-style, canonical file system path. Path values are distinct from string values, even if they contain the same sequence of bytes. Operations that produce paths will simplify the result as the standard C function realpath would, except that there is no symbolic link resolution.

Paths are suitable for referring to local files, and are often preferable over strings.

  • Path values do not contain trailing or duplicate slashes, ., or ...
  • Relative path literals are automatically resolved relative to their base directory.
  • Tooling can recognize path literals and provide additional features, such as autocompletion, refactoring automation and jump-to-file.

A file is not required to exist at a given path in order for that path value to be valid, but a path that is converted to a string with string interpolation or string-and-path concatenation must resolve to a readable file or directory which will be copied into the Nix store. For instance, evaluating "${./foo.txt}" will cause foo.txt from the same directory to be copied into the Nix store and result in the string "/nix/store/<hash>-foo.txt". Operations such as import can also expect a path to resolve to a readable file or directory.

Note

The Nix language assumes that all input files will remain unchanged while evaluating a Nix expression. For example, assume you used a file path in an interpolated string during a nix repl session. Later in the same session, after having changed the file contents, evaluating the interpolated string with the file path again might not return a new store path, since Nix might not re-read the file contents. Use :r to reset the repl as needed.

Path values can be expressed as path literals. The function builtins.isPath can be used to determine if a value is a path.

Null

There is a single value of type null in the Nix language.

This value is available as an attribute on the builtins attribute set as builtins.null.

Compound values

Attribute set

An attribute set can be constructed with an attribute set literal. The function builtins.isAttrs can be used to determine if a value is an attribute set.

List

A list can be constructed with a list literal. The function builtins.isList can be used to determine if a value is a list.

Function

A function can be constructed with a function expression. The function builtins.isFunction can be used to determine if a value is a function.

External

An external value is an opaque value created by a Nix plugin. Such a value can be substituted in Nix expressions but only created and used by plugin code.

String context

Note

This is an advanced topic. The Nix language is designed to be used without the programmer consciously dealing with string contexts or even knowing what they are.

A string in the Nix language is not just a sequence of characters like strings in other languages. It is actually a pair of a sequence of characters and a string context. The string context is an (unordered) set of string context elements.

The purpose of string contexts is to collect non-string values attached to strings via string concatenation, string interpolation, and similar operations. The idea is that a user can combine together values to create a build instructions for derivations without manually keeping track of where they come from. Then the Nix language implicitly does that bookkeeping to efficiently obtain the closure of derivation inputs.

Note

String contexts are not explicitly manipulated in idiomatic Nix language code.

String context elements come in different forms:

  • deriving path

    A string context element of this type is a deriving path. They can be either of type constant or output, which correspond to the types of deriving paths.

    • Constant string context elements

      Example

      builtins.storePath creates a string with a single constant string context element:

      builtins.getContext (builtins.storePath "/nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10")
      

      evaluates to

      {
        "/nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10" = {
          path = true;
        };
      }
      
    • Output string context elements

      Example

      The behavior of string contexts are best demonstrated with a built-in function that is still experimental: builtins.outputOf. This example will not work with stable Nix!

      builtins.getContext
        (builtins.outputOf
          (builtins.storePath "/nix/store/fvchh9cvcr7kdla6n860hshchsba305w-hello-2.12.drv")
          "out")
      

      evaluates to

      {
        "/nix/store/fvchh9cvcr7kdla6n860hshchsba305w-hello-2.12.drv" = {
          outputs = [ "out" ];
        };
      }
      
  • derivation deep

    derivation deep is an advanced feature intended to be used with the exportReferencesGraph derivation attribute. A derivation deep string context element is a derivation path, and refers to both its outputs and the entire build closure of that derivation: all its outputs, all the other derivations the given derivation depends on, and all the outputs of those.

    Example

    The best way to illustrate derivation deep string contexts is with builtins.addDrvOutputDependencies. Take a regular constant string context element pointing to a derivation, and transform it into a "Derivation deep" string context element.

    builtins.getContext
      (builtins.addDrvOutputDependencies
        (builtins.storePath "/nix/store/fvchh9cvcr7kdla6n860hshchsba305w-hello-2.12.drv"))
    

    evaluates to

    {
      "/nix/store/fvchh9cvcr7kdla6n860hshchsba305w-hello-2.12.drv" = {
        allOutputs = true;
      };
    }
    

Inspecting string contexts

Most basically, builtins.hasContext will tell whether a string has a non-empty context.

When more granular information is needed, builtins.getContext can be used. It creates an attribute set representing the string context, which can be inspected as usual.

Clearing string contexts

buitins.unsafeDiscardStringContext will make a copy of a string, but with an empty string context. The returned string can be used in more ways, e.g. by operators that require the string context to be empty. The requirement to explicitly discard the string context in such use cases helps ensure that string context elements are not lost by mistake. The "unsafe" marker is only there to remind that Nix normally guarantees that dependencies are tracked, whereas the returned string has lost them.

Constructing string contexts

builtins.appendContext will create a copy of a string, but with additional string context elements. The context is specified explicitly by an attribute set in the format that builtins.hasContext produces. A string with arbitrary contexts can be made like this:

  1. Create a string with the desired string context elements. (The contents of the string do not matter.)
  2. Dump its context with builtins.getContext.
  3. Combine it with a base string and repeated builtins.appendContext calls.

Language Constructs

This section covers syntax and semantics of the Nix language.

Basic Literals

String

See String literals.

Number

Numbers, which can be integers (like 123) or floating point (like 123.43 or .27e13).

Integers in the Nix language are 64-bit two's complement signed integers, with a range of -9223372036854775808 to 9223372036854775807, inclusive.

Note that negative numeric literals are actually parsed as unary negation of positive numeric literals. This means that the minimum integer -9223372036854775808 cannot be written as-is as a literal, since the positive number 9223372036854775808 is one past the maximum range.

See arithmetic and comparison operators for semantics.

Path

Paths can be expressed by path literals such as ./builder.sh.

A path literal must contain at least one slash to be recognised as such. For instance, builder.sh is not a path: it's parsed as an expression that selects the attribute sh from the variable builder.

Path literals are resolved relative to their base directory. Path literals may also refer to absolute paths by starting with a slash.

Note

Absolute paths make expressions less portable. In the case where a function translates a path literal into an absolute path string for a configuration file, it is recommended to write a string literal instead. This avoids some confusion about whether files at that location will be used during evaluation. It also avoids unintentional situations where some function might try to copy everything at the location into the store.

If the first component of a path is a ~, it is interpreted such that the rest of the path were relative to the user's home directory. For example, ~/foo would be equivalent to /home/edolstra/foo for a user whose home directory is /home/edolstra. Path literals that start with ~ are not allowed in pure evaluation.

Path literals can also include [string interpolation], besides being interpolated into other expressions.

At least one slash (/) must appear before any interpolated expression for the result to be recognized as a path.

a.${foo}/b.${bar} is a syntactically valid number division operation. ./a.${foo}/b.${bar} is a path.

Lookup path literals such as <nixpkgs> also resolve to path values.

List

Lists are formed by enclosing a whitespace-separated list of values between square brackets. For example,

[ 123 ./foo.nix "abc" (f { x = y; }) ]

defines a list of four elements, the last being the result of a call to the function f. Note that function calls have to be enclosed in parentheses. If they had been omitted, e.g.,

[ 123 ./foo.nix "abc" f { x = y; } ]

the result would be a list of five elements, the fourth one being a function and the fifth being a set.

Note that lists are only lazy in values, and they are strict in length.

Elements in a list can be accessed using builtins.elemAt.

Attribute Set

An attribute set is a collection of name-value-pairs called attributes.

Attribute sets are written enclosed in curly brackets ({ }). Attribute names and attribute values are separated by an equal sign (=). Each value can be an arbitrary expression, terminated by a semicolon (;)

An attribute name is a string without context, and is denoted by a name (an identifier or string literal).

Syntax

attrset{ { name = expr ; } }

Attributes can appear in any order. An attribute name may only occur once in each attribute set.

Example

This defines an attribute set with attributes named:

  • x with the value 123, an integer
  • text with the value "Hello", a string
  • y where the value is the result of applying the function f to the attribute set { bla = 456; }
{
  x = 123;
  text = "Hello";
  y = f { bla = 456; };
}

Attributes in nested attribute sets can be written using attribute paths.

Syntax

attrset{ { attrpath = expr ; } }

An attribute path is a dot-separated list of names.

Syntax

attrpath = name { . name }

Example

{ a.b.c = 1; a.b.d = 2; }
{
  a = {
    b = {
      c = 1;
      d = 2;
    };
  };
}

Attribute names can also be set implicitly by using the inherit keyword.

Example

{ inherit (builtins) true; }
{ true = true; }

Attributes can be accessed with the . operator.

Example:

{ a = "Foo"; b = "Bar"; }.a

This evaluates to "Foo".

It is possible to provide a default value in an attribute selection using the or keyword.

Example:

{ a = "Foo"; b = "Bar"; }.c or "Xyzzy"
{ a = "Foo"; b = "Bar"; }.c.d.e.f.g or "Xyzzy"

will both evaluate to "Xyzzy" because there is no c attribute in the set.

You can use arbitrary double-quoted strings as attribute names:

{ "$!@#?" = 123; }."$!@#?"
let bar = "bar"; in
{ "foo ${bar}" = 123; }."foo ${bar}"

Both will evaluate to 123.

Attribute names support [string interpolation]:

let bar = "foo"; in
{ foo = 123; }.${bar}
let bar = "foo"; in
{ ${bar} = 123; }.foo

Both will evaluate to 123.

In the special case where an attribute name inside of a set declaration evaluates to null (which is normally an error, as null cannot be coerced to a string), that attribute is simply not added to the set:

{ ${if foo then "bar" else null} = true; }

This will evaluate to {} if foo evaluates to false.

A set that has a __functor attribute whose value is callable (i.e. is itself a function or a set with a __functor attribute whose value is callable) can be applied as if it were a function, with the set itself passed in first , e.g.,

let add = { __functor = self: x: x + self.x; };
    inc = add // { x = 1; };
in inc 1

evaluates to 2. This can be used to attach metadata to a function without the caller needing to treat it specially, or to implement a form of object-oriented programming, for example.

Recursive sets

Recursive sets are like normal attribute sets, but the attributes can refer to each other.

rec-attrset = rec { [ name = expr ; ]... }

Example:

rec {
  x = y;
  y = 123;
}.x

This evaluates to 123.

Note that without rec the binding x = y; would refer to the variable y in the surrounding scope, if one exists, and would be invalid if no such variable exists. That is, in a normal (non-recursive) set, attributes are not added to the lexical scope; in a recursive set, they are.

Recursive sets of course introduce the danger of infinite recursion. For example, the expression

rec {
  x = y;
  y = x;
}.x

will crash with an infinite recursion encountered error message.

Let-expressions

A let-expression allows you to define local variables for an expression.

let-in = let [ identifier = expr ]... in expr

Example:

let
  x = "foo";
  y = "bar";
in x + y

This evaluates to "foobar".

Inheriting attributes

When defining an attribute set or in a let-expression it is often convenient to copy variables from the surrounding lexical scope (e.g., when you want to propagate attributes). This can be shortened using the inherit keyword.

Example:

let x = 123; in
{
  inherit x;
  y = 456;
}

is equivalent to

let x = 123; in
{
  x = x;
  y = 456;
}

and both evaluate to { x = 123; y = 456; }.

Note

This works because x is added to the lexical scope by the let construct.

It is also possible to inherit attributes from another attribute set.

Example:

In this fragment from all-packages.nix,

graphviz = (import ../tools/graphics/graphviz) {
  inherit fetchurl stdenv libpng libjpeg expat x11 yacc;
  inherit (xorg) libXaw;
};

xorg = {
  libX11 = ...;
  libXaw = ...;
  ...
}

libpng = ...;
libjpg = ...;
...

the set used in the function call to the function defined in ../tools/graphics/graphviz inherits a number of variables from the surrounding scope (fetchurl ... yacc), but also inherits libXaw (the X Athena Widgets) from the xorg set.

Summarizing the fragment

...
inherit x y z;
inherit (src-set) a b c;
...

is equivalent to

...
x = x; y = y; z = z;
a = src-set.a; b = src-set.b; c = src-set.c;
...

when used while defining local variables in a let-expression or while defining a set.

In a let expression, inherit can be used to selectively bring specific attributes of a set into scope. For example

let
  x = { a = 1; b = 2; };
  inherit (builtins) attrNames;
in
{
  names = attrNames x;
}

is equivalent to

let
  x = { a = 1; b = 2; };
in
{
  names = builtins.attrNames x;
}

both evaluate to { names = [ "a" "b" ]; }.

Functions

Functions have the following form:

pattern: body

The pattern specifies what the argument of the function must look like, and binds variables in the body to (parts of) the argument. There are three kinds of patterns:

  • If a pattern is a single identifier, then the function matches any argument. Example:

    let negate = x: !x;
        concat = x: y: x + y;
    in if negate true then concat "foo" "bar" else ""
    

    Note that concat is a function that takes one argument and returns a function that takes another argument. This allows partial parameterisation (i.e., only filling some of the arguments of a function); e.g.,

    map (concat "foo") [ "bar" "bla" "abc" ]
    

    evaluates to [ "foobar" "foobla" "fooabc" ].

  • A set pattern of the form { name1, name2, …, nameN } matches a set containing the listed attributes, and binds the values of those attributes to variables in the function body. For example, the function

    { x, y, z }: z + y + x
    

    can only be called with a set containing exactly the attributes x, y and z. No other attributes are allowed. If you want to allow additional arguments, you can use an ellipsis (...):

    { x, y, z, ... }: z + y + x
    

    This works on any set that contains at least the three named attributes.

    It is possible to provide default values for attributes, in which case they are allowed to be missing. A default value is specified by writing name ? e, where e is an arbitrary expression. For example,

    { x, y ? "foo", z ? "bar" }: z + y + x
    

    specifies a function that only requires an attribute named x, but optionally accepts y and z.

  • An @-pattern provides a means of referring to the whole value being matched:

    args@{ x, y, z, ... }: z + y + x + args.a
    

    but can also be written as:

    { x, y, z, ... } @ args: z + y + x + args.a
    

    Here args is bound to the argument as passed, which is further matched against the pattern { x, y, z, ... }. The @-pattern makes mainly sense with an ellipsis(...) as you can access attribute names as a, using args.a, which was given as an additional attribute to the function.

    Warning

    args@ binds the name args to the attribute set that is passed to the function. In particular, args does not include any default values specified with ? in the function's set pattern.

    For instance

    let
      f = args@{ a ? 23, ... }: [ a args ];
    in
      f {}
    

    is equivalent to

    let
      f = args @ { ... }: [ (args.a or 23) args ];
    in
      f {}
    

    and both expressions will evaluate to:

    [ 23 {} ]
    

Note that functions do not have names. If you want to give them a name, you can bind them to an attribute, e.g.,

let concat = { x, y }: x + y;
in concat { x = "foo"; y = "bar"; }

Conditionals

Conditionals look like this:

if e1 then e2 else e3

where e1 is an expression that should evaluate to a Boolean value (true or false).

Assertions

Assertions are generally used to check that certain requirements on or between features and dependencies hold. They look like this:

assert e1; e2

where e1 is an expression that should evaluate to a Boolean value. If it evaluates to true, e2 is returned; otherwise expression evaluation is aborted and a backtrace is printed.

Here is a Nix expression for the Subversion package that shows how assertions can be used:.

{ localServer ? false
, httpServer ? false
, sslSupport ? false
, pythonBindings ? false
, javaSwigBindings ? false
, javahlBindings ? false
, stdenv, fetchurl
, openssl ? null, httpd ? null, db4 ? null, expat, swig ? null, j2sdk ? null
}:

assert localServer -> db4 != null; ①
assert httpServer -> httpd != null && httpd.expat == expat; ②
assert sslSupport -> openssl != null && (httpServer -> httpd.openssl == openssl); ③
assert pythonBindings -> swig != null && swig.pythonSupport;
assert javaSwigBindings -> swig != null && swig.javaSupport;
assert javahlBindings -> j2sdk != null;

stdenv.mkDerivation {
  name = "subversion-1.1.1";
  ...
  openssl = if sslSupport then openssl else null; ④
  ...
}

The points of interest are:

  1. This assertion states that if Subversion is to have support for local repositories, then Berkeley DB is needed. So if the Subversion function is called with the localServer argument set to true but the db4 argument set to null, then the evaluation fails.

    Note that -> is the logical implication Boolean operation.

  2. This is a more subtle condition: if Subversion is built with Apache (httpServer) support, then the Expat library (an XML library) used by Subversion should be same as the one used by Apache. This is because in this configuration Subversion code ends up being linked with Apache code, and if the Expat libraries do not match, a build- or runtime link error or incompatibility might occur.

  3. This assertion says that in order for Subversion to have SSL support (so that it can access https URLs), an OpenSSL library must be passed. Additionally, it says that if Apache support is enabled, then Apache's OpenSSL should match Subversion's. (Note that if Apache support is not enabled, we don't care about Apache's OpenSSL.)

  4. The conditional here is not really related to assertions, but is worth pointing out: it ensures that if SSL support is disabled, then the Subversion derivation is not dependent on OpenSSL, even if a non-null value was passed. This prevents an unnecessary rebuild of Subversion if OpenSSL changes.

With-expressions

A with-expression,

with e1; e2

introduces the set e1 into the lexical scope of the expression e2. For instance,

let as = { x = "foo"; y = "bar"; };
in with as; x + y

evaluates to "foobar" since the with adds the x and y attributes of as to the lexical scope in the expression x + y. The most common use of with is in conjunction with the import function. E.g.,

with (import ./definitions.nix); ...

makes all attributes defined in the file definitions.nix available as if they were defined locally in a let-expression.

The bindings introduced by with do not shadow bindings introduced by other means, e.g.

let a = 3; in with { a = 1; }; let a = 4; in with { a = 2; }; ...

establishes the same scope as

let a = 1; in let a = 2; in let a = 3; in let a = 4; in ...

Variables coming from outer with expressions are shadowed:

with { a = "outer"; };
with { a = "inner"; };
a

Does evaluate to "inner".

Comments

  • Inline comments start with # and run until the end of the line.

    Example

    # A number
    2 # Equals 1 + 1
    
    2
    
  • Block comments start with /* and run until the next occurrence of */.

    Example

    /*
    Block comments
    can span multiple lines.
    */ "hello"
    
    "hello"
    

    This means that block comments cannot be nested.

    Example

    /* /* nope */ */ 1
    
    error: syntax error, unexpected '*'
    
           at «string»:1:15:
    
                1| /* /* nope */ *
                 |               ^
    

    Consider escaping nested comments and unescaping them in post-processing.

    Example

    /* /* nested *\/ */ 1
    
    1
    

Variables

A variable is an identifier used as an expression.

Syntax

expressionidentifier

A variable must have the same name as a definition in the scope that encloses it. The value of a variable is the value of the corresponding expression in the enclosing scope.

String literals

A string literal represents a string value.

Syntax

expressionstring

string" ( string_char* interpolation_element )* string_char* "

string'' ( indented_string_char* interpolation_element )* indented_string_char* ''

stringuri

string_char ~ [^"$\\]|\$(?!\{)|\\.

indented_string_char ~ [^$']|\$\$|\$(?!\{)|''[$']|''\\.|'(?!')

uri ~ [A-Za-z][+\-.0-9A-Za-z]*:[!$%&'*+,\-./0-9:=?@A-Z_a-z~]+

Strings can be written in three ways.

The most common way is to enclose the string between double quotes, e.g., "foo bar". Strings can span multiple lines. The results of other expressions can be included into a string by enclosing them in ${ }, a feature known as string interpolation.

The following must be escaped to represent them within a string, by prefixing with a backslash (\):

  • Double quote (")

Example

"\""
"\""
  • Backslash (\)

Example

"\\"
"\\"
  • Dollar sign followed by an opening curly bracket (${) – "dollar-curly"

Example

"\${"
"\${"

The newline, carriage return, and tab characters can be written as \n, \r and \t, respectively.

A "double-dollar-curly" ($${) can be written literally.

Example

"$${"
"$\${"

String values are output on the terminal with Nix-specific escaping. Strings written to files will contain the characters encoded by the escaping.

The second way to write string literals is as an indented string, which is enclosed between pairs of double single-quotes (''), like so:

''
This is the first line.
This is the second line.
  This is the third line.
''

This kind of string literal intelligently strips indentation from the start of each line. To be precise, it strips from each line a number of spaces equal to the minimal indentation of the string as a whole (disregarding the indentation of empty lines). For instance, the first and second line are indented two spaces, while the third line is indented four spaces. Thus, two spaces are stripped from each line, so the resulting string is

"This is the first line.\nThis is the second line.\n  This is the third line.\n"

Note

Whitespace and newline following the opening '' is ignored if there is no non-whitespace text on the initial line.

Warning

Prefixed tab characters are not stripped.

Example

The following indented string is prefixed with tabs:

''
	all:
		@echo hello
''
"\tall:\n\t\t@echo hello\n"

Indented strings support string interpolation.

The following must be escaped to represent them in an indented string:

  • $ is escaped by prefixing it with two single quotes ('')

Example

''
  ''$
''
"$\n"
  • '' is escaped by prefixing it with one single quote (')

Example

''
  '''
''
"''\n"

These special characters are escaped as follows:

  • Linefeed (\n): ''\n
  • Carriage return (\r): ''\r
  • Tab (\t): ''\t

''\ escapes any other character.

A "dollar-curly" (${) can be written as follows:

Example

''
  echo ''${PATH}
''
"echo ${PATH}\n"

Note

This differs from the syntax for escaping a dollar-curly within double quotes ("\${"). Be aware of which one is needed at a given moment.

A "double-dollar-curly" ($${) can be written literally.

Example

''
  $${
''
"$\${\n"

Indented strings are primarily useful in that they allow multi-line string literals to follow the indentation of the enclosing Nix expression, and that less escaping is typically necessary for strings representing languages such as shell scripts and configuration files because '' is much less common than ". Example:

stdenv.mkDerivation {
...
postInstall =
  ''
    mkdir $out/bin $out/etc
    cp foo $out/bin
    echo "Hello World" > $out/etc/foo.conf
    ${if enableBar then "cp bar $out/bin" else ""}
  '';
...
}

Finally, as a convenience, URIs as defined in appendix B of RFC 2396 can be written as is, without quotes. For instance, the string "http://example.org/foo.tar.bz2" can also be written as http://example.org/foo.tar.bz2.

Identifiers

An identifier is an ASCII character sequence that:

  • Starts with a letter (a-z, A-Z) or underscore (_)
  • Can contain any number of:
    • Letters (a-z, A-Z)
    • Digits (0-9)
    • Underscores (_)
    • Apostrophes (')
    • Hyphens (-)
  • Is not one of the keywords

Syntax

identifier ~ [A-Za-z_][A-Za-z0-9_'-]*

Names

A name can be written as an identifier or a string literal.

Syntax

nameidentifier | string

Names are used in attribute sets, let bindings, and inherit. Two names are the same if they represent the same sequence of characters, regardless of whether they are written as identifiers or strings.

Keywords

These keywords are reserved and cannot be used as identifiers:

Note

The Nix language evaluator currently allows or to be used as a name in some contexts, for backwards compatibility reasons. Users are advised not to rely on this.

There are long-standing issues with how or is parsed as a name, which can't be resolved without making a breaking change to the language.

Scoping rules

A scope in the Nix language is a dictionary keyed by name, mapping each name to an expression and a definition type. The definition type is either explicit or implicit. Each entry in this dictionary is a definition.

Explicit definitions are created by the following expressions:

Implicit definitions are only created by with-expressions.

Every expression is enclosed by a scope. The outermost expression is enclosed by the built-in, global scope, which contains only explicit definitions. The expressions listed above extend their enclosing scope by adding new definitions, or replacing existing ones with the same name. An explicit definition can replace a definition of any type; an implicit definition can only replace another implicit definition.

Each of the above expressions defines which of its subexpressions are enclosed by the extended scope. In all other cases, the same scope that encloses an expression is the enclosing scope for its subexpressions.

The Nix language is statically scoped; the value of a variable is determined only by the variable's enclosing scope, and not by the dynamic context in which the variable is evaluated.

Note

Expressions entered into the Nix REPL are enclosed by a scope that can be extended by command line arguments or previous REPL commands. These ways of extending scope are not, strictly speaking, part of the Nix language.

String interpolation

String interpolation is a language feature where a string, path, or attribute name can contain expressions enclosed in ${ } (dollar-sign with curly brackets).

Such a construct is called interpolated string, and the expression inside is an interpolated expression.

Syntax

interpolation_element${ expression }

Examples

String

Rather than writing

"--with-freetype2-library=" + freetype + "/lib"

(where freetype is a derivation expression), you can instead write

"--with-freetype2-library=${freetype}/lib"

The latter is automatically translated to the former.

A more complicated example (from the Nix expression for Qt):

configureFlags = "
  -system-zlib -system-libpng -system-libjpeg
  ${if openglSupport then "-dlopen-opengl
    -L${mesa}/lib -I${mesa}/include
    -L${libXmu}/lib -I${libXmu}/include" else ""}
  ${if threadSupport then "-thread" else "-no-thread"}
";

Note that Nix expressions and strings can be arbitrarily nested; in this case the outer string contains various interpolated expressions that themselves contain strings (e.g., "-thread"), some of which in turn contain interpolated expressions (e.g., ${mesa}).

To write a literal ${ in an regular string, escape it with a backslash (\).

Example

"echo \${PATH}"
"echo ${PATH}"

To write a literal ${ in an indented string, escape it with two single quotes ('').

Example

''
  echo ''${PATH}
''
"echo ${PATH}\n"

$${ can be written literally in any string.

Example

In Make, $ in file names or recipes is represented as $$, see GNU make: Basics of Variable Reference. This can be expressed directly in the Nix language strings:

''
  MAKEVAR = Hello
  all:
  	@export BASHVAR=world; echo $(MAKEVAR) $${BASHVAR}
''
"MAKEVAR = Hello\nall:\n\t@export BASHVAR=world; echo $(MAKEVAR) $\${BASHVAR}\n"

See the documentation on strings for details.

Path

Rather than writing

./. + "/" + foo + "-" + bar + ".nix"

or

./. + "/${foo}-${bar}.nix"

you can instead write

./${foo}-${bar}.nix

Attribute name

Attribute names can be interpolated strings.

Example

let name = "foo"; in
{ ${name} = 123; }
{ foo = 123; }

Attributes can be selected with interpolated strings.

Example

let name = "foo"; in
{ foo = 123; }.${name}
123

Interpolated expression

An expression that is interpolated must evaluate to one of the following:

A string interpolates to itself.

A path in an interpolated expression is first copied into the Nix store, and the resulting string is the store path of the newly created store object.

Example

$ mkdir foo

Reference the empty directory in an interpolated expression:

"${./foo}"
"/nix/store/2hhl2nz5v0khbn06ys82nrk99aa1xxdw-foo"

A derivation interpolates to the store path of its first output.

Example

let
  pkgs = import <nixpkgs> {};
in
"${pkgs.hello}"
"/nix/store/4xpfqf29z4m8vbhrqcz064wfmb46w5r7-hello-2.12.1"

An attribute set interpolates to the return value of the function in the __toString applied to the attribute set itself.

Example

let
  a = {
    value = 1;
    __toString = self: toString (self.value + 1);
  };
in
"${a}"
"2"

An attribute set also interpolates to the value of its outPath attribute.

Example

let
  a = { outPath = "foo"; };
in
"${a}"
"foo"

If both __toString and outPath are present in an attribute set, __toString takes precedence.

Example

let
  a = { __toString = _: "yes"; outPath = throw "no"; };
in
"${a}"
"yes"

If neither is present, an error is thrown.

Example

let
  a = {};
in
"${a}"
error: cannot coerce a set to a string: { }

       at «string»:4:2:

            3| in
            4| "${a}"
             |  ^

Lookup path

Syntax

lookup-path = < identifier [ / identifier ]... >

A lookup path is an identifier with an optional path suffix that resolves to a path value if the identifier matches a search path entry in builtins.nixPath. The algorithm for lookup path resolution is described in the documentation on builtins.findFile.

Example

<nixpkgs>
/nix/var/nix/profiles/per-user/root/channels/nixpkgs

Example

<nixpkgs/nixos>
/nix/var/nix/profiles/per-user/root/channels/nixpkgs/nixos

Operators

NameSyntaxAssociativityPrecedence
Attribute selectionattrset . attrpath [ or expr ]none1
Function applicationfunc exprleft2
Arithmetic negation- numbernone3
Has attributeattrset ? attrpathnone4
List concatenationlist ++ listright5
Multiplicationnumber * numberleft6
Divisionnumber / numberleft6
Subtractionnumber - numberleft7
Additionnumber + numberleft7
String concatenationstring + stringleft7
Path concatenationpath + pathleft7
Path and string concatenationpath + stringleft7
String and path concatenationstring + pathleft7
Logical negation (NOT)! boolnone8
Updateattrset // attrsetright9
Less thanexpr < exprnone10
Less than or equal toexpr <= exprnone10
Greater thanexpr > exprnone10
Greater than or equal toexpr >= exprnone10
Equalityexpr == exprnone11
Inequalityexpr != exprnone11
Logical conjunction (AND)bool && boolleft12
Logical disjunction (OR)bool || boolleft13
Logical implicationbool -> boolright14
Pipe operator (experimental)expr |> funcleft15
Pipe operator (experimental)func <| exprright15

Attribute selection

Syntax

attrset . attrpath [ or expr ]

Select the attribute denoted by attribute path attrpath from attribute set attrset. If the attribute doesn’t exist, return the expr after or if provided, otherwise abort evaluation.

Function application

Syntax

func expr

Apply the callable value func to the argument expr. Note the absence of any visible operator symbol. A callable value is either:

Warning

List items are also separated by whitespace, which means that function calls in list items must be enclosed by parentheses.

Has attribute

Syntax

attrset ? attrpath

Test whether attribute set attrset contains the attribute denoted by attrpath. The result is a Boolean value.

See also: builtins.hasAttr

After evaluating attrset and attrpath, the computational complexity is O(log(n)) for n attributes in the attrset

Arithmetic

Numbers will retain their type unless mixed with other numeric types: Pure integer operations will always return integers, whereas any operation involving at least one floating point number returns a floating point number.

Evaluation of the following numeric operations throws an evaluation error:

  • Division by zero
  • Integer overflow, that is, any operation yielding a result outside of the representable range of Nix language integers

See also Comparison and Equality.

The + operator is overloaded to also work on strings and paths.

String concatenation

Syntax

string + string

Concatenate two strings and merge their string contexts.

Path concatenation

Syntax

path + path

Concatenate two paths. The result is a path.

Path and string concatenation

Syntax

path + string

Concatenate path with string. The result is a path.

Note

The string must not have a string context that refers to a store path.

String and path concatenation

Syntax

string + path

Concatenate string with path. The result is a string.

Important

The file or directory at path must exist and is copied to the store. The path appears in the result as the corresponding store path.

Update

Syntax

attrset1 // attrset2

Update attribute set attrset1 with names and values from attrset2.

The returned attribute set will have all of the attributes in attrset1 and attrset2. If an attribute name is present in both, the attribute value from the latter is taken.

Comparison

Comparison is

  • arithmetic for numbers
  • lexicographic for strings and paths
  • item-wise lexicographic for lists: elements at the same index in both lists are compared according to their type and skipped if they are equal.

All comparison operators are implemented in terms of <, and the following equivalencies hold:

comparisonimplementation
a <= b! ( b < a )
a > bb < a
a >= b! ( a < b )

Equality

  • Attribute sets and lists are compared recursively, and therefore are fully evaluated.
  • Comparison of functions always returns false.
  • Numbers are type-compatible, see arithmetic operators.
  • Floating point numbers only differ up to a limited precision.

Logical implication

Equivalent to !b1 || b2.

Pipe operators

  • a |> b is equivalent to b a
  • a <| b is equivalent to a b

Example

nix-repl> 1 |> builtins.add 2 |> builtins.mul 3
9

nix-repl> builtins.add 1 <| builtins.mul 2 <| 3
7

Warning

This syntax is part of an experimental feature and may change in future releases.

To use this syntax, make sure the pipe-operators experimental feature is enabled. For example, include the following in nix.conf:

extra-experimental-features = pipe-operators

Built-ins

This section lists the values and functions built into the Nix language evaluator. All built-ins are available through the global builtins constant.

Some built-ins are also exposed directly in the global scope:

derivation attrs

derivation is described in its own section.

abort s

Abort Nix expression evaluation and print the error message s.

add e1 e2

Return the sum of the numbers e1 and e2.

addDrvOutputDependencies s

Create a copy of the given string where a single constant string context element is turned into a derivation deep string context element.

The store path that is the constant string context element should point to a valid derivation, and end in .drv.

The original string context element must not be empty or have multiple elements, and it must not have any other type of element other than a constant or derivation deep element. The latter is supported so this function is idempotent.

This is the opposite of builtins.unsafeDiscardOutputDependency.

all pred list

Return true if the function pred returns true for all elements of list, and false otherwise.

any pred list

Return true if the function pred returns true for at least one element of list, and false otherwise.

attrNames set

Return the names of the attributes in the set set in an alphabetically sorted list. For instance, builtins.attrNames { y = 1; x = "foo"; } evaluates to [ "x" "y" ].

attrValues set

Return the values of the attributes in the set set in the order corresponding to the sorted attribute names.

baseNameOf x

Return the base name of either a path value x or a string x, depending on which type is passed, and according to the following rules.

For a path value, the base name is considered to be the part of the path after the last directory separator, including any file extensions. This is the simple case, as path values don't have trailing slashes.

When the argument is a string, a more involved logic applies. If the string ends with a /, only this one final slash is removed.

After this, the base name is returned as previously described, assuming / as the directory separator. (Note that evaluation must be platform independent.)

This is somewhat similar to the GNU basename command, but GNU basename will strip any number of trailing slashes.

bitAnd e1 e2

Return the bitwise AND of the integers e1 and e2.

bitOr e1 e2

Return the bitwise OR of the integers e1 and e2.

bitXor e1 e2

Return the bitwise XOR of the integers e1 and e2.

break v

In debug mode (enabled using --debugger), pause Nix expression evaluation and enter the REPL. Otherwise, return the argument v.

builtins (set)

Contains all the built-in functions and values.

Since built-in functions were added over time, testing for attributes in builtins can be used for graceful fallback on older Nix installations:

# if hasContext is not available, we assume `s` has a context
if builtins ? hasContext then builtins.hasContext s else true
catAttrs attr list

Collect each attribute named attr from a list of attribute sets. Attrsets that don't contain the named attribute are ignored. For example,

builtins.catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}]

evaluates to [1 2].

ceil double

Converts an IEEE-754 double-precision floating-point number (double) to the next higher integer.

If the datatype is neither an integer nor a "float", an evaluation error will be thrown.

compareVersions s1 s2

Compare two strings representing versions and return -1 if version s1 is older than version s2, 0 if they are the same, and 1 if s1 is newer than s2. The version comparison algorithm is the same as the one used by nix-env -u.

concatLists lists

Concatenate a list of lists into a single list.

concatMap f list

This function is equivalent to builtins.concatLists (map f list) but is more efficient.

concatStringsSep separator list

Concatenate a list of strings with a separator between each element, e.g. concatStringsSep "/" ["usr" "local" "bin"] == "usr/local/bin".

convertHash args

Return the specified representation of a hash string, based on the attributes presented in args:

  • hash

    The hash to be converted. The hash format is detected automatically.

  • hashAlgo

    The algorithm used to create the hash. Must be one of

    • "md5"
    • "sha1"
    • "sha256"
    • "sha512"

    The attribute may be omitted when hash is an SRI hash or when the hash is prefixed with the hash algorithm name followed by a colon. That <hashAlgo>:<hashBody> syntax is supported for backwards compatibility with existing tooling.

  • toHashFormat

    The format of the resulting hash. Must be one of

    • "base16"
    • "nix32"
    • "base32" (deprecated alias for "nix32")
    • "base64"
    • "sri"

The result hash is the toHashFormat representation of the hash hash.

Example

Convert a SHA256 hash in Base16 to SRI:

builtins.convertHash {
  hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  toHashFormat = "sri";
  hashAlgo = "sha256";
}
"sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="

Example

Convert a SHA256 hash in SRI to Base16:

builtins.convertHash {
  hash = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
  toHashFormat = "base16";
}
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"

Example

Convert a hash in the form <hashAlgo>:<hashBody> in Base16 to SRI:

builtins.convertHash {
  hash = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  toHashFormat = "sri";
}
"sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
currentSystem (string)

The value of the eval-system or else system configuration option.

It can be used to set the system attribute for builtins.derivation such that the resulting derivation can be built on the same system that evaluates the Nix expression:

 builtins.derivation {
   # ...
   system = builtins.currentSystem;
}

It can be overridden in order to create derivations for different system than the current one:

$ nix-instantiate --system "mips64-linux" --eval --expr 'builtins.currentSystem'
"mips64-linux"

Note

Not available in pure evaluation mode.

currentTime (integer)

Return the Unix time at first evaluation. Repeated references to that name will re-use the initially obtained value.

Example:

$ nix repl
Welcome to Nix 2.15.1 Type :? for help.

nix-repl> builtins.currentTime
1683705525

nix-repl> builtins.currentTime
1683705525

The store path of a derivation depending on currentTime will differ for each evaluation, unless both evaluate builtins.currentTime in the same second.

Note

Not available in pure evaluation mode.

deepSeq e1 e2

This is like seq e1 e2, except that e1 is evaluated deeply: if it’s a list or set, its elements or attributes are also evaluated recursively.

dirOf s

Return the directory part of the string s, that is, everything before the final slash in the string. This is similar to the GNU dirname command.

div e1 e2

Return the quotient of the numbers e1 and e2.

elem x xs

Return true if a value equal to x occurs in the list xs, and false otherwise.

elemAt xs n

Return element n from the list xs. Elements are counted starting from 0. A fatal error occurs if the index is out of bounds.

false (Boolean)

Primitive value.

It can be returned by comparison operators and used in conditional expressions.

The name false is not special, and can be shadowed:

nix-repl> let false = 1; in false
1
fetchClosure args

Note

This function is only available if the fetch-closure experimental feature is enabled.

For example, include the following in nix.conf:

extra-experimental-features = fetch-closure

Fetch a store path closure from a binary cache, and return the store path as a string with context.

This function can be invoked in three ways, that we will discuss in order of preference.

Fetch a content-addressed store path

Example:

builtins.fetchClosure {
  fromStore = "https://cache.nixos.org";
  fromPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1;
}

This is the simplest invocation, and it does not require the user of the expression to configure trusted-public-keys to ensure their authenticity.

If your store path is input addressed instead of content addressed, consider the other two invocations.

Fetch any store path and rewrite it to a fully content-addressed store path

Example:

builtins.fetchClosure {
  fromStore = "https://cache.nixos.org";
  fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1;
  toPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1;
}

This example fetches /nix/store/r2jd... from the specified binary cache, and rewrites it into the content-addressed store path /nix/store/ldbh....

Like the previous example, no extra configuration or privileges are required.

To find out the correct value for toPath given a fromPath, use nix store make-content-addressed:

# nix store make-content-addressed --from https://cache.nixos.org /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1
rewrote '/nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1' to '/nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1'

Alternatively, set toPath = "" and find the correct toPath in the error message.

Fetch an input-addressed store path as is

Example:

builtins.fetchClosure {
  fromStore = "https://cache.nixos.org";
  fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1;
  inputAddressed = true;
}

It is possible to fetch an input-addressed store path and return it as is. However, this is the least preferred way of invoking fetchClosure, because it requires that the input-addressed paths are trusted by the Nix configuration.

builtins.storePath

fetchClosure is similar to builtins.storePath in that it allows you to use a previously built store path in a Nix expression. However, fetchClosure is more reproducible because it specifies a binary cache from which the path can be fetched. Also, using content-addressed store paths does not require users to configure trusted-public-keys to ensure their authenticity.

fetchGit args

Fetch a path from git. args can be a URL, in which case the HEAD of the repo at that URL is fetched. Otherwise, it can be an attribute with the following attributes (all except url optional):

  • url

    The URL of the repo.

  • name (default: source)

    The name of the directory the repo should be exported to in the store.

  • rev (default: the tip of ref)

    The Git revision to fetch. This is typically a commit hash.

  • ref (default: HEAD)

    The Git reference under which to look for the requested revision. This is often a branch or tag name.

    This option has no effect once shallow cloning is enabled.

    By default, the ref value is prefixed with refs/heads/. As of 2.3.0, Nix will not prefix refs/heads/ if ref starts with refs/.

  • submodules (default: false)

    A Boolean parameter that specifies whether submodules should be checked out.

  • exportIgnore (default: true)

    A Boolean parameter that specifies whether export-ignore from .gitattributes should be applied. This approximates part of the git archive behavior.

    Enabling this option is not recommended because it is unknown whether the Git developers commit to the reproducibility of export-ignore in newer Git versions.

  • shallow (default: false)

    Make a shallow clone when fetching the Git tree. When this is enabled, the options ref and allRefs have no effect anymore.

  • lfs (default: false)

    A boolean that when true specifies that Git LFS files should be fetched.

  • allRefs

    Whether to fetch all references (eg. branches and tags) of the repository. With this argument being true, it's possible to load a rev from any ref. (by default only revs from the specified ref are supported).

    This option has no effect once shallow cloning is enabled.

  • verifyCommit (default: true if publicKey or publicKeys are provided, otherwise false)

    Whether to check rev for a signature matching publicKey or publicKeys. If verifyCommit is enabled, then fetchGit cannot use a local repository with uncommitted changes. Requires the verified-fetches experimental feature.

  • publicKey

    The public key against which rev is verified if verifyCommit is enabled. Requires the verified-fetches experimental feature.

  • keytype (default: "ssh-ed25519")

    The key type of publicKey. Possible values:

  • publicKeys

    The public keys against which rev is verified if verifyCommit is enabled. Must be given as a list of attribute sets with the following form:

    {
      key = "<public key>";
      type = "<key type>"; # optional, default: "ssh-ed25519"
    }
    

    Requires the verified-fetches experimental feature.

Here are some examples of how to use fetchGit.

  • To fetch a private repository over SSH:

    builtins.fetchGit {
      url = "git@github.com:my-secret/repository.git";
      ref = "master";
      rev = "adab8b916a45068c044658c4158d81878f9ed1c3";
    }
    
  • To fetch an arbitrary reference:

    builtins.fetchGit {
      url = "https://github.com/NixOS/nix.git";
      ref = "refs/heads/0.5-release";
    }
    
  • If the revision you're looking for is in the default branch of the git repository you don't strictly need to specify the branch name in the ref attribute.

    However, if the revision you're looking for is in a future branch for the non-default branch you will need to specify the the ref attribute as well.

    builtins.fetchGit {
      url = "https://github.com/nixos/nix.git";
      rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
      ref = "1.11-maintenance";
    }
    

    Note

    It is nice to always specify the branch which a revision belongs to. Without the branch being specified, the fetcher might fail if the default branch changes. Additionally, it can be confusing to try a commit from a non-default branch and see the fetch fail. If the branch is specified the fault is much more obvious.

  • If the revision you're looking for is in the default branch of the git repository you may omit the ref attribute.

    builtins.fetchGit {
      url = "https://github.com/nixos/nix.git";
      rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
    }
    
  • To fetch a specific tag:

    builtins.fetchGit {
      url = "https://github.com/nixos/nix.git";
      ref = "refs/tags/1.9";
    }
    
  • To fetch the latest version of a remote branch:

    builtins.fetchGit {
      url = "ssh://git@github.com/nixos/nix.git";
      ref = "master";
    }
    
  • To verify the commit signature:

    builtins.fetchGit {
      url = "ssh://git@github.com/nixos/nix.git";
      verifyCommit = true;
      publicKeys = [
          {
            type = "ssh-ed25519";
            key = "AAAAC3NzaC1lZDI1NTE5AAAAIArPKULJOid8eS6XETwUjO48/HKBWl7FTCK0Z//fplDi";
          }
      ];
    }
    

    Nix will refetch the branch according to the tarball-ttl setting.

    This behavior is disabled in pure evaluation mode.

  • To fetch the content of a checked-out work directory:

    builtins.fetchGit ./work-dir
    

If the URL points to a local directory, and no ref or rev is given, fetchGit will use the current content of the checked-out files, even if they are not committed or added to Git's index. It will only consider files added to the Git repository, as listed by git ls-files.

fetchTarball args

Download the specified URL, unpack it and return the path of the unpacked tree. The file must be a tape archive (.tar) compressed with gzip, bzip2 or xz. If the tarball consists of a single directory, then the top-level path component of the files in the tarball is removed. The typical use of the function is to obtain external Nix expression dependencies, such as a particular version of Nixpkgs, e.g.

with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {};

stdenv.mkDerivation { … }

The fetched tarball is cached for a certain amount of time (1 hour by default) in ~/.cache/nix/tarballs/. You can change the cache timeout either on the command line with --tarball-ttl number-of-seconds or in the Nix configuration file by adding the line tarball-ttl = number-of-seconds.

Note that when obtaining the hash with nix-prefetch-url the option --unpack is required.

This function can also verify the contents against a hash. In that case, the function takes a set instead of a URL. The set requires the attribute url and the attribute sha256, e.g.

with import (fetchTarball {
  url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz";
  sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {};

stdenv.mkDerivation { … }

Not available in restricted evaluation mode.

fetchTree input

Fetch a file system tree or a plain file using one of the supported backends and return an attribute set with:

  • the resulting fixed-output store path
  • the corresponding NAR hash
  • backend-specific metadata (currently not documented).

input must be an attribute set with the following attributes:

  • type (String, required)

    One of the supported source types. This determines other required and allowed input attributes.

  • narHash (String, optional)

    The narHash parameter can be used to substitute the source of the tree. It also allows for verification of tree contents that may not be provided by the underlying transfer mechanism. If narHash is set, the source is first looked up is the Nix store and substituters, and only fetched if not available.

A subset of the output attributes of fetchTree can be re-used for subsequent calls to fetchTree to produce the same result again. That is, fetchTree is idempotent.

Downloads are cached in $XDG_CACHE_HOME/nix. The remote source will be fetched from the network if both are true:

  • A NAR hash is supplied and the corresponding store path is not valid, that is, not available in the store

    Note

    Substituters are not used in fetching.

  • There is no cache entry or the cache entry is older than tarball-ttl

Source types

The following source types and associated input attributes are supported.

  • "file"

    Place a plain file into the Nix store. This is similar to builtins.fetchurl

    • url (String, required)

      Supported protocols:

      • https

        Example

        fetchTree {
          type = "file";
          url = "https://example.com/index.html";
        }
        
      • http

        Insecure HTTP transfer for legacy sources.

        Warning

        HTTP performs no encryption or authentication. Use a narHash known in advance to ensure the output has expected contents.

      • file

        A file on the local file system.

        Example

        fetchTree {
          type = "file";
          url = "file:///home/eelco/nix/README.md";
        }
        
  • "tarball"

    Download a tar archive and extract it into the Nix store. This has the same underyling implementation as builtins.fetchTarball

    • url (String, required)

      Example

      fetchTree {
        type = "tarball";
        url = "https://github.com/NixOS/nixpkgs/tarball/nixpkgs-23.11";
      }
      
  • "git"

    Fetch a Git tree and copy it to the Nix store. This is similar to builtins.fetchGit.

    • url (String, required)

      The URL formats supported are the same as for Git itself.

      Example

      fetchTree {
        type = "git";
        url = "git@github.com:NixOS/nixpkgs.git";
      }
      

      Note

      If the URL points to a local directory, and no ref or rev is given, Nix will only consider files added to the Git index, as listed by git ls-files but use the current file contents of the Git working directory.

    • ref (String, optional)

      By default, this has no effect. This becomes relevant only once shallow cloning is disabled.

      A Git reference, such as a branch or tag name.

      Default: "HEAD"

    • rev (String, optional)

      A Git revision; a commit hash.

      Default: the tip of ref

    • shallow (Bool, optional)

      Make a shallow clone when fetching the Git tree. When this is enabled, the options ref and allRefs have no effect anymore.

      Default: true

    • submodules (Bool, optional)

      Also fetch submodules if available.

      Default: false

    • lfs (Bool, optional)

      Fetch any Git LFS files.

      Default: false

    • allRefs (Bool, optional)

      By default, this has no effect. This becomes relevant only once shallow cloning is disabled.

      Whether to fetch all references (eg. branches and tags) of the repository. With this argument being true, it's possible to load a rev from any ref. (Without setting this option, only revs from the specified ref are supported).

      Default: false

    • lastModified (Integer, optional)

      Unix timestamp of the fetched commit.

      If set, pass through the value to the output attribute set. Otherwise, generated from the fetched Git tree.

    • revCount (Integer, optional)

      Number of revisions in the history of the Git repository before the fetched commit.

      If set, pass through the value to the output attribute set. Otherwise, generated from the fetched Git tree.

The following input types are still subject to change:

  • "path"
  • "github"
  • "gitlab"
  • "sourcehut"
  • "mercurial"

input can also be a URL-like reference.

Example

Fetch a GitHub repository using the attribute set representation:

builtins.fetchTree {
  type = "github";
  owner = "NixOS";
  repo = "nixpkgs";
  rev = "ae2e6b3958682513d28f7d633734571fb18285dd";
}

This evaluates to the following attribute set:

{
  lastModified = 1686503798;
  lastModifiedDate = "20230611171638";
  narHash = "sha256-rA9RqKP9OlBrgGCPvfd5HVAXDOy8k2SmPtB/ijShNXc=";
  outPath = "/nix/store/l5m6qlvfs9sdw14ja3qbzpglcjlb6j1x-source";
  rev = "ae2e6b3958682513d28f7d633734571fb18285dd";
  shortRev = "ae2e6b3";
}

Example

Fetch the same GitHub repository using the URL-like syntax:

builtins.fetchTree "github:NixOS/nixpkgs/ae2e6b3958682513d28f7d633734571fb18285dd"
fetchurl arg

Download the specified URL and return the path of the downloaded file. arg can be either a string denoting the URL, or an attribute set with the following attributes:

  • url

    The URL of the file to download.

  • name (default: the last path component of the URL)

    A name for the file in the store. This can be useful if the URL has any characters that are invalid for the store.

Not available in restricted evaluation mode.

filter f list

Return a list consisting of the elements of list for which the function f returns true.

filterSource e1 e2

Warning

filterSource should not be used to filter store paths. Since filterSource uses the name of the input directory while naming the output directory, doing so will produce a directory name in the form of <hash2>-<hash>-<name>, where <hash>-<name> is the name of the input directory. Since <hash> depends on the unfiltered directory, the name of the output directory will indirectly depend on files that are filtered out by the function. This will trigger a rebuild even when a filtered out file is changed. Use builtins.path instead, which allows specifying the name of the output directory.

This function allows you to copy sources into the Nix store while filtering certain files. For instance, suppose that you want to use the directory source-dir as an input to a Nix expression, e.g.

stdenv.mkDerivation {
  ...
  src = ./source-dir;
}

However, if source-dir is a Subversion working copy, then all those annoying .svn subdirectories will also be copied to the store. Worse, the contents of those directories may change a lot, causing lots of spurious rebuilds. With filterSource you can filter out the .svn directories:

src = builtins.filterSource
  (path: type: type != "directory" || baseNameOf path != ".svn")
  ./source-dir;

Thus, the first argument e1 must be a predicate function that is called for each regular file, directory or symlink in the source tree e2. If the function returns true, the file is copied to the Nix store, otherwise it is omitted. The function is called with two arguments. The first is the full path of the file. The second is a string that identifies the type of the file, which is either "regular", "directory", "symlink" or "unknown" (for other kinds of files such as device nodes or fifos — but note that those cannot be copied to the Nix store, so if the predicate returns true for them, the copy will fail). If you exclude a directory, the entire corresponding subtree of e2 will be excluded.

findFile search-path lookup-path

Find lookup-path in search-path.

Lookup path expressions are desugared using this and builtins.nixPath:

<nixpkgs>

is equivalent to:

builtins.findFile builtins.nixPath "nixpkgs"

A search path is represented as a list of attribute sets with two attributes:

  • prefix is a relative path.
  • path denotes a file system location

Examples of search path attribute sets:

  • {
      prefix = "";
      path = "/nix/var/nix/profiles/per-user/root/channels";
    }
    
  • {
      prefix = "nixos-config";
      path = "/etc/nixos/configuration.nix";
    }
    
  • {
      prefix = "nixpkgs";
      path = "https://github.com/NixOS/nixpkgs/tarballs/master";
    }
    
  • {
      prefix = "nixpkgs";
      path = "channel:nixpkgs-unstable";
    }
    
  • {
      prefix = "flake-compat";
      path = "flake:github:edolstra/flake-compat";
    }
    

The lookup algorithm checks each entry until a match is found, returning a path value of the match:

  • If a prefix of lookup-path matches prefix, then the remainder of lookup-path (the "suffix") is searched for within the directory denoted by path. The contents of path may need to be downloaded at this point to look inside.

  • If the suffix is found inside that directory, then the entry is a match. The combined absolute path of the directory (now downloaded if need be) and the suffix is returned.

Example

A search-path value

[
  {
    prefix = "";
    path = "/home/eelco/Dev";
  }
  {
    prefix = "nixos-config";
    path = "/etc/nixos";
  }
]

and a lookup-path value "nixos-config" will cause Nix to try /home/eelco/Dev/nixos-config and /etc/nixos in that order and return the first path that exists.

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 consist of a single top-level directory.

The URLs of the tarballs from the official nixos.org channels can be abbreviated as channel:<channel-name>. See documentation on nix-channel for details about channels.

Example

These two search path entries are equivalent:

  • {
      prefix = "nixpkgs";
      path = "channel:nixpkgs-unstable";
    }
    
  • {
      prefix = "nixpkgs";
      path = "https://nixos.org/channels/nixos-unstable/nixexprs.tar.xz";
    }
    

Search paths can also point to source trees using flake URLs.

Example

The search path entry

{
  prefix = "nixpkgs";
  path = "flake:nixpkgs";
}

specifies that the prefix nixpkgs shall refer to the source tree downloaded from the nixpkgs entry in the flake registry.

Similarly

{
  prefix = "nixpkgs";
  path = "flake:github:nixos/nixpkgs/nixos-22.05";
}

makes <nixpkgs> refer to a particular branch of the NixOS/nixpkgs repository on GitHub.

flakeRefToString attrs

Convert a flake reference from attribute set format to URL format.

For example:

builtins.flakeRefToString {
  dir = "lib"; owner = "NixOS"; ref = "23.05"; repo = "nixpkgs"; type = "github";
}

evaluates to

"github:NixOS/nixpkgs/23.05?dir=lib"
floor double

Converts an IEEE-754 double-precision floating-point number (double) to the next lower integer.

If the datatype is neither an integer nor a "float", an evaluation error will be thrown.

foldl' op nul list

Reduce a list by applying a binary operator, from left to right, e.g. foldl' op nul [x0 x1 x2 ...] = op (op (op nul x0) x1) x2) ....

For example, foldl' (acc: elem: acc + elem) 0 [1 2 3] evaluates to 6 and foldl' (acc: elem: { "${elem}" = elem; } // acc) {} ["a" "b"] evaluates to { a = "a"; b = "b"; }.

The first argument of op is the accumulator whereas the second argument is the current element being processed. The return value of each application of op is evaluated immediately, even for intermediate values.

fromJSON e

Convert a JSON string to a Nix value. For example,

builtins.fromJSON ''{"x": [1, 2, 3], "y": null}''

returns the value { x = [ 1 2 3 ]; y = null; }.

fromTOML e

Convert a TOML string to a Nix value. For example,

builtins.fromTOML ''
  x=1
  s="a"
  [table]
  y=2
''

returns the value { s = "a"; table = { y = 2; }; x = 1; }.

functionArgs f

Return a set containing the names of the formal arguments expected by the function f. The value of each attribute is a Boolean denoting whether the corresponding argument has a default value. For instance, functionArgs ({ x, y ? 123}: ...) = { x = false; y = true; }.

"Formal argument" here refers to the attributes pattern-matched by the function. Plain lambdas are not included, e.g. functionArgs (x: ...) = { }.

genList generator length

Generate list of size length, with each element i equal to the value returned by generator i. For example,

builtins.genList (x: x * x) 5

returns the list [ 0 1 4 9 16 ].

genericClosure attrset

builtins.genericClosure iteratively computes the transitive closure over an arbitrary relation defined by a function.

It takes attrset with two attributes named startSet and operator, and returns a list of attribute sets:

  • startSet: The initial list of attribute sets.

  • operator: A function that takes an attribute set and returns a list of attribute sets. It defines how each item in the current set is processed and expanded into more items.

Each attribute set in the list startSet and the list returned by operator must have an attribute key, which must support equality comparison. The value of key can be one of the following types:

The result is produced by calling the operator on each item that has not been called yet, including newly added items, until no new items are added. Items are compared by their key attribute.

Common usages are:

  • Generating unique collections of items, such as dependency graphs.
  • Traversing through structures that may contain cycles or loops.
  • Processing data structures with complex internal relationships.

Example

builtins.genericClosure {
  startSet = [ {key = 5;} ];
  operator = item: [{
    key = if (item.key / 2 ) * 2 == item.key
         then item.key / 2
         else 3 * item.key + 1;
  }];
}

evaluates to

[ { key = 5; } { key = 16; } { key = 8; } { key = 4; } { key = 2; } { key = 1; } ]
getAttr s set

getAttr returns the attribute named s from set. Evaluation aborts if the attribute doesn’t exist. This is a dynamic version of the . operator, since s is an expression rather than an identifier.

getContext s

Return the string context of s.

The string context tracks references to derivations within a string. It is represented as an attribute set of store derivation paths mapping to output names.

Using string interpolation on a derivation will add that derivation to the string context. For example,

builtins.getContext "${derivation { name = "a"; builder = "b"; system = "c"; }}"

evaluates to

{ "/nix/store/arhvjaf6zmlyn8vh8fgn55rpwnxq0n7l-a.drv" = { outputs = [ "out" ]; }; }
getEnv s

getEnv returns the value of the environment variable s, or an empty string if the variable doesn’t exist. This function should be used with care, as it can introduce all sorts of nasty environment dependencies in your Nix expression.

getEnv is used in Nix Packages to locate the file ~/.nixpkgs/config.nix, which contains user-local settings for Nix Packages. (That is, it does a getEnv "HOME" to locate the user’s home directory.)

getFlake args

Fetch a flake from a flake reference, and return its output attributes and some metadata. For example:

(builtins.getFlake "nix/55bc52401966fbffa525c574c14f67b00bc4fb3a").packages.x86_64-linux.nix

Unless impure evaluation is allowed (--impure), the flake reference must be "locked", e.g. contain a Git revision or content hash. An example of an unlocked usage is:

(builtins.getFlake "github:edolstra/dwarffs").rev
groupBy f list

Groups elements of list together by the string returned from the function f called on each element. It returns an attribute set where each attribute value contains the elements of list that are mapped to the same corresponding attribute name returned by f.

For example,

builtins.groupBy (builtins.substring 0 1) ["foo" "bar" "baz"]

evaluates to

{ b = [ "bar" "baz" ]; f = [ "foo" ]; }
hasAttr s set

hasAttr returns true if set has an attribute named s, and false otherwise. This is a dynamic version of the ? operator, since s is an expression rather than an identifier.

hasContext s

Return true if string s has a non-empty context. The context can be obtained with getContext.

Example

Many operations require a string context to be empty because they are intended only to work with "regular" strings, and also to help users avoid unintentionally loosing track of string context elements. builtins.hasContext can help create better domain-specific errors in those case.

name: meta:

if builtins.hasContext name
then throw "package name cannot contain string context"
else { ${name} = meta; }
hashFile type p

Return a base-16 representation of the cryptographic hash of the file at path p. The hash algorithm specified by type must be one of "md5", "sha1", "sha256" or "sha512".

hashString type s

Return a base-16 representation of the cryptographic hash of string s. The hash algorithm specified by type must be one of "md5", "sha1", "sha256" or "sha512".

head list

Return the first element of a list; abort evaluation if the argument isn’t a list or is an empty list. You can test whether a list is empty by comparing it with [].

import path

Load, parse, and return the Nix expression in the file path.

Note

Unlike some languages, import is a regular function in Nix.

The path argument must meet the same criteria as an interpolated expression.

If path is a directory, the file default.nix in that directory is used if it exists.

Example

$ echo 123 > default.nix

Import default.nix from the current directory.

import ./.
123

Evaluation aborts if the file doesn’t exist or contains an invalid Nix expression.

A Nix expression loaded by import must not contain any free variables, that is, identifiers that are not defined in the Nix expression itself and are not built-in. Therefore, it cannot refer to variables that are in scope at the call site.

Example

If you have a calling expression

rec {
  x = 123;
  y = import ./foo.nix;
}

then the following foo.nix will give an error:

# foo.nix
x + 456

since x is not in scope in foo.nix. If you want x to be available in foo.nix, pass it as a function argument:

rec {
  x = 123;
  y = import ./foo.nix x;
}

and

# foo.nix
x: x + 456

The function argument doesn’t have to be called x in foo.nix; any name would work.

intersectAttrs e1 e2

Return a set consisting of the attributes in the set e2 which have the same name as some attribute in e1.

Performs in O(n log m) where n is the size of the smaller set and m the larger set's size.

isAttrs e

Return true if e evaluates to a set, and false otherwise.

isBool e

Return true if e evaluates to a bool, and false otherwise.

isFloat e

Return true if e evaluates to a float, and false otherwise.

isFunction e

Return true if e evaluates to a function, and false otherwise.

isInt e

Return true if e evaluates to an integer, and false otherwise.

isList e

Return true if e evaluates to a list, and false otherwise.

isNull e

Return true if e evaluates to null, and false otherwise.

This is equivalent to e == null.

isPath e

Return true if e evaluates to a path, and false otherwise.

isString e

Return true if e evaluates to a string, and false otherwise.

langVersion (integer)

The current version of the Nix language.

length e

Return the length of the list e.

lessThan e1 e2

Return true if the number e1 is less than the number e2, and false otherwise. Evaluation aborts if either e1 or e2 does not evaluate to a number.

listToAttrs e

Construct a set from a list specifying the names and values of each attribute. Each element of the list should be a set consisting of a string-valued attribute name specifying the name of the attribute, and an attribute value specifying its value.

In case of duplicate occurrences of the same name, the first takes precedence.

Example:

builtins.listToAttrs
  [ { name = "foo"; value = 123; }
    { name = "bar"; value = 456; }
    { name = "bar"; value = 420; }
  ]

evaluates to

{ foo = 123; bar = 456; }
map f list

Apply the function f to each element in the list list. For example,

map (x: "foo" + x) [ "bar" "bla" "abc" ]

evaluates to [ "foobar" "foobla" "fooabc" ].

mapAttrs f attrset

Apply function f to every element of attrset. For example,

builtins.mapAttrs (name: value: value * 10) { a = 1; b = 2; }

evaluates to { a = 10; b = 20; }.

match regex str

Returns a list if the extended POSIX regular expression regex matches str precisely, otherwise returns null. Each item in the list is a regex group.

builtins.match "ab" "abc"

Evaluates to null.

builtins.match "abc" "abc"

Evaluates to [ ].

builtins.match "a(b)(c)" "abc"

Evaluates to [ "b" "c" ].

builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" "  FOO   "

Evaluates to [ "FOO" ].

mul e1 e2

Return the product of the numbers e1 and e2.

nixPath (list)

A list of search path entries used to resolve lookup paths. Its value is primarily determined by the nix-path configuration setting, which are

  • Overridden by the NIX_PATH environment variable or the --nix-path option
  • Extended by the -I option or --extra-nix-path

Example

$ NIX_PATH= nix-instantiate --eval --expr "builtins.nixPath" -I foo=bar --no-pure-eval
[ { path = "bar"; prefix = "foo"; } ]

Lookup path expressions are desugared using this and builtins.findFile:

<nixpkgs>

is equivalent to:

builtins.findFile builtins.nixPath "nixpkgs"
nixVersion (string)

The version of Nix.

For example, where the command line returns the current Nix version,

$ nix --version
nix (Nix) 2.16.0

the Nix language evaluator returns the same value:

nix-repl> builtins.nixVersion
"2.16.0"
null (null)

Primitive value.

The name null is not special, and can be shadowed:

nix-repl> let null = 1; in null
1
outputOf derivation-reference output-name

Note

This function is only available if the dynamic-derivations experimental feature is enabled.

For example, include the following in nix.conf:

extra-experimental-features = dynamic-derivations

Return the output path of a derivation, literally or using an input placeholder string if needed.

If the derivation has a statically-known output path (i.e. the derivation output is input-addressed, or fixed content-addresed), the output path will just be returned. But if the derivation is content-addressed or if the derivation is itself not-statically produced (i.e. is the output of another derivation), an input placeholder will be returned instead.

derivation reference must be a string that may contain a regular store path to a derivation, or may be an input placeholder reference. If the derivation is produced by a derivation, you must explicitly select drv.outPath. This primop can be chained arbitrarily deeply. For instance,

builtins.outputOf
  (builtins.outputOf myDrv "out")
  "out"

will return a input placeholder for the output of the output of myDrv.

This primop corresponds to the ^ sigil for deriving paths, e.g. as part of installable syntax on the command line.

parseDrvName s

Split the string s into a package name and version. The package name is everything up to but not including the first dash not followed by a letter, and the version is everything following that dash. The result is returned in a set { name, version }. Thus, builtins.parseDrvName "nix-0.12pre12876" returns { name = "nix"; version = "0.12pre12876"; }.

parseFlakeRef flake-ref

Parse a flake reference, and return its exploded form.

For example:

builtins.parseFlakeRef "github:NixOS/nixpkgs/23.05?dir=lib"

evaluates to:

{ dir = "lib"; owner = "NixOS"; ref = "23.05"; repo = "nixpkgs"; type = "github"; }
partition pred list

Given a predicate function pred, this function returns an attrset containing a list named right, containing the elements in list for which pred returned true, and a list named wrong, containing the elements for which it returned false. For example,

builtins.partition (x: x > 10) [1 23 9 3 42]

evaluates to

{ right = [ 23 42 ]; wrong = [ 1 9 3 ]; }
path args

An enrichment of the built-in path type, based on the attributes present in args. All are optional except path:

  • path
    The underlying path.

  • name
    The name of the path when added to the store. This can used to reference paths that have nix-illegal characters in their names, like @.

  • filter
    A function of the type expected by builtins.filterSource, with the same semantics.

  • recursive
    When false, when path is added to the store it is with a flat hash, rather than a hash of the NAR serialization of the file. Thus, path must refer to a regular file, not a directory. This allows similar behavior to fetchurl. Defaults to true.

  • sha256
    When provided, this is the expected hash of the file at the path. Evaluation will fail if the hash is incorrect, and providing a hash allows builtins.path to be used even when the pure-eval nix config option is on.

pathExists path

Return true if the path path exists at evaluation time, and false otherwise.

placeholder output

Return at output placeholder string for the specified output that will be substituted by the corresponding output path at build time.

Typical outputs would be "out", "bin" or "dev".

readDir path

Return the contents of the directory path as a set mapping directory entries to the corresponding file type. For instance, if directory A contains a regular file B and another directory C, then builtins.readDir ./A will return the set

{ B = "regular"; C = "directory"; }

The possible values for the file type are "regular", "directory", "symlink" and "unknown".

readFile path

Return the contents of the file path as a string.

readFileType p

Determine the directory entry type of a filesystem node, being one of "directory", "regular", "symlink", or "unknown".

removeAttrs set list

Remove the attributes listed in list from set. The attributes don’t have to exist in set. For instance,

removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ]

evaluates to { y = 2; }.

replaceStrings from to s

Given string s, replace every occurrence of the strings in from with the corresponding string in to.

The argument to is lazy, that is, it is only evaluated when its corresponding pattern in from is matched in the string s

Example:

builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"

evaluates to "fabir".

seq e1 e2

Evaluate e1, then evaluate and return e2. This ensures that a computation is strict in the value of e1.

sort comparator list

Return list in sorted order. It repeatedly calls the function comparator with two elements. The comparator should return true if the first element is less than the second, and false otherwise. For example,

builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ]

produces the list [ 42 77 147 249 483 526 ].

This is a stable sort: it preserves the relative order of elements deemed equal by the comparator.

split regex str

Returns a list composed of non matched strings interleaved with the lists of the extended POSIX regular expression regex matches of str. Each item in the lists of matched sequences is a regex group.

builtins.split "(a)b" "abc"

Evaluates to [ "" [ "a" ] "c" ].

builtins.split "([ac])" "abc"

Evaluates to [ "" [ "a" ] "b" [ "c" ] "" ].

builtins.split "(a)|(c)" "abc"

Evaluates to [ "" [ "a" null ] "b" [ null "c" ] "" ].

builtins.split "([[:upper:]]+)" " FOO "

Evaluates to [ " " [ "FOO" ] " " ].

splitVersion s

Split a string representing a version into its components, by the same version splitting logic underlying the version comparison in nix-env -u.

storeDir (string)

Logical file system location of the Nix store currently in use.

This value is determined by the store parameter in Store URLs:

$ nix-instantiate --store 'dummy://?store=/blah' --eval --expr builtins.storeDir
"/blah"
storePath path

This function allows you to define a dependency on an already existing store path. For example, the derivation attribute src = builtins.storePath /nix/store/f1d18v1y…-source causes the derivation to depend on the specified path, which must exist or be substitutable. Note that this differs from a plain path (e.g. src = /nix/store/f1d18v1y…-source) in that the latter causes the path to be copied again to the Nix store, resulting in a new path (e.g. /nix/store/ld01dnzc…-source-source).

Not available in pure evaluation mode.

See also builtins.fetchClosure.

stringLength e

Return the number of bytes of the string e. If e is not a string, evaluation is aborted.

sub e1 e2

Return the difference between the numbers e1 and e2.

substring start len s

Return the substring of s from byte position start (zero-based) up to but not including start + len. If start is greater than the length of the string, an empty string is returned. If start + len lies beyond the end of the string or len is -1, only the substring up to the end of the string is returned. start must be non-negative. For example,

builtins.substring 0 3 "nixos"

evaluates to "nix".

tail list

Return the list without its first item; abort evaluation if the argument isn’t a list or is an empty list.

Warning

This function should generally be avoided since it's inefficient: unlike Haskell's tail, it takes O(n) time, so recursing over a list by repeatedly calling tail takes O(n^2) time.

throw s

Throw an error message s. This usually aborts Nix expression evaluation, but in nix-env -qa and other commands that try to evaluate a set of derivations to get information about those derivations, a derivation that throws an error is silently skipped (which is not the case for abort).

toFile name s

Store the string s in a file in the Nix store and return its path. The file has suffix name. This file can be used as an input to derivations. One application is to write builders “inline”. For instance, the following Nix expression combines the Nix expression for GNU Hello and its build script into one file:

{ stdenv, fetchurl, perl }:

stdenv.mkDerivation {
  name = "hello-2.1.1";

  builder = builtins.toFile "builder.sh" "
    source $stdenv/setup

    PATH=$perl/bin:$PATH

    tar xvfz $src
    cd hello-*
    ./configure --prefix=$out
    make
    make install
  ";

  src = fetchurl {
    url = "http://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
    sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
  };
  inherit perl;
}

It is even possible for one file to refer to another, e.g.,

builder = let
  configFile = builtins.toFile "foo.conf" "
    # This is some dummy configuration file.
    ...
  ";
in builtins.toFile "builder.sh" "
  source $stdenv/setup
  ...
  cp ${configFile} $out/etc/foo.conf
";

Note that ${configFile} is a string interpolation, so the result of the expression configFile (i.e., a path like /nix/store/m7p7jfny445k...-foo.conf) will be spliced into the resulting string.

It is however not allowed to have files mutually referring to each other, like so:

let
  foo = builtins.toFile "foo" "...${bar}...";
  bar = builtins.toFile "bar" "...${foo}...";
in foo

This is not allowed because it would cause a cyclic dependency in the computation of the cryptographic hashes for foo and bar.

It is also not possible to reference the result of a derivation. If you are using Nixpkgs, the writeTextFile function is able to do that.

toJSON e

Return a string containing a JSON representation of e. Strings, integers, floats, booleans, nulls and lists are mapped to their JSON equivalents. Sets (except derivations) are represented as objects. Derivations are translated to a JSON string containing the derivation’s output path. Paths are copied to the store and represented as a JSON string of the resulting store path.

toPath s

DEPRECATED. Use /. + "/path" to convert a string into an absolute path. For relative paths, use ./. + "/path".

toString e

Convert the expression e to a string. e can be:

  • A string (in which case the string is returned unmodified).

  • A path (e.g., toString /foo/bar yields "/foo/bar".

  • A set containing { __toString = self: ...; } or { outPath = ...; }.

  • An integer.

  • A list, in which case the string representations of its elements are joined with spaces.

  • A Boolean (false yields "", true yields "1").

  • null, which yields the empty string.

toXML e

Return a string containing an XML representation of e. The main application for toXML is to communicate information with the builder in a more structured format than plain environment variables.

Here is an example where this is the case:

{ stdenv, fetchurl, libxslt, jira, uberwiki }:

stdenv.mkDerivation (rec {
  name = "web-server";

  buildInputs = [ libxslt ];

  builder = builtins.toFile "builder.sh" "
    source $stdenv/setup
    mkdir $out
    echo "$servlets" | xsltproc ${stylesheet} - > $out/server-conf.xml ①
  ";

  stylesheet = builtins.toFile "stylesheet.xsl" ②
   "<?xml version='1.0' encoding='UTF-8'?>
    <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
      <xsl:template match='/'>
        <Configure>
          <xsl:for-each select='/expr/list/attrs'>
            <Call name='addWebApplication'>
              <Arg><xsl:value-of select=\"attr[@name = 'path']/string/@value\" /></Arg>
              <Arg><xsl:value-of select=\"attr[@name = 'war']/path/@value\" /></Arg>
            </Call>
          </xsl:for-each>
        </Configure>
      </xsl:template>
    </xsl:stylesheet>
  ";

  servlets = builtins.toXML [ ③
    { path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; }
    { path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
  ];
})

The builder is supposed to generate the configuration file for a Jetty servlet container. A servlet container contains a number of servlets (*.war files) each exported under a specific URI prefix. So the servlet configuration is a list of sets containing the path and war of the servlet (①). This kind of information is difficult to communicate with the normal method of passing information through an environment variable, which just concatenates everything together into a string (which might just work in this case, but wouldn’t work if fields are optional or contain lists themselves). Instead the Nix expression is converted to an XML representation with toXML, which is unambiguous and can easily be processed with the appropriate tools. For instance, in the example an XSLT stylesheet (at point ②) is applied to it (at point ①) to generate the XML configuration file for the Jetty server. The XML representation produced at point ③ by toXML is as follows:

<?xml version='1.0' encoding='utf-8'?>
<expr>
  <list>
    <attrs>
      <attr name="path">
        <string value="/bugtracker" />
      </attr>
      <attr name="war">
        <path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
      </attr>
    </attrs>
    <attrs>
      <attr name="path">
        <string value="/wiki" />
      </attr>
      <attr name="war">
        <path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />
      </attr>
    </attrs>
  </list>
</expr>

Note that we used the toFile built-in to write the builder and the stylesheet “inline” in the Nix expression. The path of the stylesheet is spliced into the builder using the syntax xsltproc ${stylesheet}.

trace e1 e2

Evaluate e1 and print its abstract syntax representation on standard error. Then return e2. This function is useful for debugging.

If the debugger-on-trace option is set to true and the --debugger flag is given, the interactive debugger will be started when trace is called (like break).

traceVerbose e1 e2

Evaluate e1 and print its abstract syntax representation on standard error if --trace-verbose is enabled. Then return e2. This function is useful for debugging.

true (Boolean)

Primitive value.

It can be returned by comparison operators and used in conditional expressions.

The name true is not special, and can be shadowed:

nix-repl> let true = 1; in true
1
tryEval e

Try to shallowly evaluate e. Return a set containing the attributes success (true if e evaluated successfully, false if an error was thrown) and value, equalling e if successful and false otherwise. tryEval will only prevent errors created by throw or assert from being thrown. Errors tryEval will not catch are for example those created by abort and type errors generated by builtins. Also note that this doesn't evaluate e deeply, so let e = { x = throw ""; }; in (builtins.tryEval e).success will be true. Using builtins.deepSeq one can get the expected result: let e = { x = throw ""; }; in (builtins.tryEval (builtins.deepSeq e e)).success will be false.

tryEval intentionally does not return the error message, because that risks bringing non-determinism into the evaluation result, and it would become very difficult to improve error reporting without breaking existing expressions. Instead, use builtins.addErrorContext to add context to the error message, and use a Nix unit testing tool for testing.

typeOf e

Return a string representing the type of the value e, namely "int", "bool", "string", "path", "null", "set", "list", "lambda" or "float".

unsafeDiscardOutputDependency s

Create a copy of the given string where every derivation deep string context element is turned into a constant string context element.

This is the opposite of builtins.addDrvOutputDependencies.

This is unsafe because it allows us to "forget" store objects we would have otherwise referred to with the string context, whereas Nix normally tracks all dependencies consistently. Safe operations "grow" but never "shrink" string contexts. builtins.addDrvOutputDependencies in contrast is safe because "derivation deep" string context element always refers to the underlying derivation (among many more things). Replacing a constant string context element with a "derivation deep" element is a safe operation that just enlargens the string context without forgetting anything.

unsafeDiscardStringContext s

Discard the string context from a value that can be coerced to a string.

warn e1 e2

Evaluate e1, which must be a string, and print it on standard error as a warning. Then return e2. This function is useful for non-critical situations where attention is advisable.

If the debugger-on-trace or debugger-on-warn option is set to true and the --debugger flag is given, the interactive debugger will be started when warn is called (like break).

If the abort-on-warn option is set, the evaluation will be aborted after the warning is printed. This is useful to reveal the stack trace of the warning, when the context is non-interactive and a debugger can not be launched.

zipAttrsWith f list

Transpose a list of attribute sets into an attribute set of lists, then apply mapAttrs.

f receives two arguments: the attribute name and a non-empty list of all values encountered for that attribute name.

The result is an attribute set where the attribute names are the union of the attribute names in each element of list. The attribute values are the return values of f.

builtins.zipAttrsWith
  (name: values: { inherit name values; })
  [ { a = "x"; } { a = "y"; b = "z"; } ]

evaluates to

{
  a = { name = "a"; values = [ "x" "y" ]; };
  b = { name = "b"; values = [ "z" ]; };
}

Derivations

The most important built-in function is derivation, which is used to describe a single store-layer store derivation. Consult the store chapter for what a store derivation is; this section just concerns how to create one from the Nix language.

This builtin function takes as input an attribute set, the attributes of which specify the inputs to the process. It outputs an attribute set, and produces a store derivation as a side effect of evaluation.

Input attributes

Required

  • name (String)

    A symbolic name for the derivation. See derivation outputs for what this is affects.

    Example

    derivation {
      name = "hello";
      # ...
    }
    

    The derivation's path will be /nix/store/<hash>-hello.drv. The output paths will be of the form /nix/store/<hash>-hello[-<output>]

  • system (String)

    See system.

    Example

    Declare a derivation to be built on a specific system type:

    derivation {
      # ...
      system = "x86_64-linux";
      # ...
    }
    

    Example

    Declare a derivation to be built on the system type that evaluates the expression:

    derivation {
      # ...
      system = builtins.currentSystem;
      # ...
    }
    

    builtins.currentSystem has the value of the [system configuration option], and defaults to the system type of the current Nix installation.

  • builder (Path | String)

    See builder.

    Example

    Use the file located at /bin/bash as the builder executable:

    derivation {
      # ...
      builder = "/bin/bash";
      # ...
    };
    

    Example

    Copy a local file to the Nix store for use as the builder executable:

    derivation {
      # ...
      builder = ./builder.sh;
      # ...
    };
    

    Example

    Use a file from another derivation as the builder executable:

    let pkgs = import <nixpkgs> {}; in
    derivation {
      # ...
      builder = "${pkgs.python}/bin/python";
      # ...
    };
    

Optional

  • args (List of String)

    Default: [ ]

    See args.

    Example

    Pass arguments to Bash to interpret a shell command:

    derivation {
      # ...
      builder = "/bin/bash";
      args = [ "-c" "echo hello world > $out" ];
      # ...
    };
    
  • outputs (List of String)

    Default: [ "out" ]

    Symbolic outputs of the derivation. Each output name is passed to the builder executable as an environment variable with its value set to the corresponding store path.

    By default, a derivation produces a single output called out. However, derivations can produce multiple outputs. This allows the associated store objects and their closures to be copied or garbage-collected separately.

    Example

    Imagine a library package that provides a dynamic library, header files, and documentation. A program that links against such a library doesn’t need the header files and documentation at runtime, and it doesn’t need the documentation at build time. Thus, the library package could specify:

    derivation {
      # ...
      outputs = [ "lib" "dev" "doc" ];
      # ...
    }
    

    This will cause Nix to pass environment variables lib, dev, and doc to the builder containing the intended store paths of each output. The builder would typically do something like

    ./configure \
      --libdir=$lib/lib \
      --includedir=$dev/include \
      --docdir=$doc/share/doc
    

    for an Autoconf-style package.

    The name of an output is combined with the name of the derivation to create the name part of the output's store path, unless it is out, in which case just the name of the derivation is used.

    Example

    derivation {
      name = "example";
      outputs = [ "lib" "dev" "doc" "out" ];
      # ...
    }
    

    The store derivation path will be /nix/store/<hash>-example.drv. The output paths will be

    • /nix/store/<hash>-example-lib
    • /nix/store/<hash>-example-dev
    • /nix/store/<hash>-example-doc
    • /nix/store/<hash>-example

    You can refer to each output of a derivation by selecting it as an attribute. The first element of outputs determines the default output and ends up at the top-level.

    Example

    Select an output by attribute name:

    let
      myPackage = derivation {
        name = "example";
        outputs = [ "lib" "dev" "doc" "out" ];
        # ...
      };
    in myPackage.dev
    

    Since lib is the first output, myPackage is equivalent to myPackage.lib.

  • See Advanced Attributes for more, infrequently used, optional attributes.

  • Every other attribute is passed as an environment variable to the builder. Attribute values are translated to environment variables as follows:

    • Strings are passed unchanged.

    • Integral numbers are converted to decimal notation.

    • Floating point numbers are converted to simple decimal or scientific notation with a preset precision.

    • A path (e.g., ../foo/sources.tar) causes the referenced file to be copied to the store; its location in the store is put in the environment variable. The idea is that all sources should reside in the Nix store, since all inputs to a derivation should reside in the Nix store.

    • A derivation causes that derivation to be built prior to the present derivation. The environment variable is set to the store path of the derivation's default output.

    • Lists of the previous types are also allowed. They are simply concatenated, separated by spaces.

    • true is passed as the string 1, false and null are passed as an empty string.

Advanced Attributes

Derivations can declare some infrequently used optional attributes.

  • allowedReferences
    The optional attribute allowedReferences specifies a list of legal references (dependencies) of the output of the builder. For example,

    allowedReferences = [];
    

    enforces that the output of a derivation cannot have any runtime dependencies on its inputs. To allow an output to have a runtime dependency on itself, use "out" as a list item. This is used in NixOS to check that generated files such as initial ramdisks for booting Linux don’t have accidental dependencies on other paths in the Nix store.

  • allowedRequisites
    This attribute is similar to allowedReferences, but it specifies the legal requisites of the whole closure, so all the dependencies recursively. For example,

    allowedRequisites = [ foobar ];
    

    enforces that the output of a derivation cannot have any other runtime dependency than foobar, and in addition it enforces that foobar itself doesn't introduce any other dependency itself.

  • disallowedReferences
    The optional attribute disallowedReferences specifies a list of illegal references (dependencies) of the output of the builder. For example,

    disallowedReferences = [ foo ];
    

    enforces that the output of a derivation cannot have a direct runtime dependencies on the derivation foo.

  • disallowedRequisites
    This attribute is similar to disallowedReferences, but it specifies illegal requisites for the whole closure, so all the dependencies recursively. For example,

    disallowedRequisites = [ foobar ];
    

    enforces that the output of a derivation cannot have any runtime dependency on foobar or any other derivation depending recursively on foobar.

  • exportReferencesGraph
    This attribute allows builders access to the references graph of their inputs. The attribute is a list of inputs in the Nix store whose references graph the builder needs to know. The value of this attribute should be a list of pairs [ name1 path1 name2 path2 ... ]. The references graph of each pathN will be stored in a text file nameN in the temporary build directory. The text files have the format used by nix-store --register-validity (with the deriver fields left empty). For example, when the following derivation is built:

    derivation {
      ...
      exportReferencesGraph = [ "libfoo-graph" libfoo ];
    };
    

    the references graph of libfoo is placed in the file libfoo-graph in the temporary build directory.

    exportReferencesGraph is useful for builders that want to do something with the closure of a store path. Examples include the builders in NixOS that generate the initial ramdisk for booting Linux (a cpio archive containing the closure of the boot script) and the ISO-9660 image for the installation CD (which is populated with a Nix store containing the closure of a bootable NixOS configuration).

  • impureEnvVars
    This attribute allows you to specify a list of environment variables that should be passed from the environment of the calling user to the builder. Usually, the environment is cleared completely when the builder is executed, but with this attribute you can allow specific environment variables to be passed unmodified. For example, fetchurl in Nixpkgs has the line

    impureEnvVars = [ "http_proxy" "https_proxy" ... ];
    

    to make it use the proxy server configuration specified by the user in the environment variables http_proxy and friends.

    This attribute is only allowed in fixed-output derivations, where impurities such as these are okay since (the hash of) the output is known in advance. It is ignored for all other derivations.

    Warning

    impureEnvVars implementation takes environment variables from the current builder process. When a daemon is building its environmental variables are used. Without the daemon, the environmental variables come from the environment of the nix-build.

    If the configurable-impure-env experimental feature is enabled, these environment variables can also be controlled through the impure-env configuration setting.

  • passAsFile
    A list of names of attributes that should be passed via files rather than environment variables. For example, if you have

    passAsFile = ["big"];
    big = "a very long string";
    

    then when the builder runs, the environment variable bigPath will contain the absolute path to a temporary file containing a very long string. That is, for any attribute x listed in passAsFile, Nix will pass an environment variable xPath holding the path of the file containing the value of attribute x. This is useful when you need to pass large strings to a builder, since most operating systems impose a limit on the size of the environment (typically, a few hundred kilobyte).

  • preferLocalBuild
    If this attribute is set to true and distributed building is enabled, then, if possible, the derivation will be built locally instead of being forwarded to a remote machine. This is useful for derivations that are cheapest to build locally.

  • allowSubstitutes
    If this attribute is set to false, then Nix will always build this derivation (locally or remotely); it will not try to substitute its outputs. This is useful for derivations that are cheaper to build than to substitute.

    This attribute can be ignored by setting always-allow-substitutes to true.

    Note

    If set to false, the builder should be able to run on the system type specified in the system attribute, since the derivation cannot be substituted.

  • __structuredAttrs
    If the special attribute __structuredAttrs is set to true, the other derivation attributes are serialised into a file in JSON format. The environment variable NIX_ATTRS_JSON_FILE points to the exact location of that file both in a build and a nix-shell. This obviates the need for passAsFile since JSON files have no size restrictions, unlike process environments.

    It also makes it possible to tweak derivation settings in a structured way; see outputChecks for example.

    As a convenience to Bash builders, Nix writes a script that initialises shell variables corresponding to all attributes that are representable in Bash. The environment variable NIX_ATTRS_SH_FILE points to the exact location of the script, both in a build and a nix-shell. This includes non-nested (associative) arrays. For example, the attribute hardening.format = true ends up as the Bash associative array element ${hardening[format]}.

    Warning

    If set to true, other advanced attributes such as allowedReferences, allowedReferences, allowedRequisites, disallowedReferences and disallowedRequisites, maxSize, and maxClosureSize. will have no effect.

  • outputChecks
    When using structured attributes, the outputChecks attribute allows defining checks per-output.

    In addition to allowedReferences, allowedRequisites, disallowedReferences and disallowedRequisites, the following attributes are available:

    • maxSize defines the maximum size of the resulting store object.
    • maxClosureSize defines the maximum size of the output's closure.
    • ignoreSelfRefs controls whether self-references should be considered when checking for allowed references/requisites.

    Example:

    __structuredAttrs = true;
    
    outputChecks.out = {
      # The closure of 'out' must not be larger than 256 MiB.
      maxClosureSize = 256 * 1024 * 1024;
    
      # It must not refer to the C compiler or to the 'dev' output.
      disallowedRequisites = [ stdenv.cc "dev" ];
    };
    
    outputChecks.dev = {
      # The 'dev' output must not be larger than 128 KiB.
      maxSize = 128 * 1024;
    };
    
  • unsafeDiscardReferences\

    When using structured attributes, the attribute unsafeDiscardReferences is an attribute set with a boolean value for each output name. If set to true, it disables scanning the output for runtime dependencies.

    Example:

    __structuredAttrs = true;
    unsafeDiscardReferences.out = true;
    

    This is useful, for example, when generating self-contained filesystem images with their own embedded Nix store: hashes found inside such an image refer to the embedded store and not to the host's Nix store.

  • requiredSystemFeatures\

    If a derivation has the requiredSystemFeatures attribute, then Nix will only build it on a machine that has the corresponding features set in its system-features configuration.

    For example, setting

    requiredSystemFeatures = [ "kvm" ];
    

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

Setting the derivation type

As discussed in Derivation Outputs and Types of Derivations, there are multiples kinds of derivations / kinds of derivation outputs. The choice of the following attributes determines which kind of derivation we are making.

The three types of derivations are chosen based on the following combinations of these attributes. All other combinations are invalid.

Here is more information on the output* attributes, and what values they may be set to:

Import From Derivation

The value of a Nix expression can depend on the contents of a store object.

Passing an expression expr that evaluates to a store path to any built-in function which reads from the filesystem constitutes Import From Derivation (IFD):

When the store path needs to be accessed, evaluation will be paused, the corresponding store object realised, and then evaluation resumed.

This has performance implications: Evaluation can only finish when all required store objects are realised. Since the Nix language evaluator is sequential, it only finds store paths to read from one at a time. While realisation is always parallel, in this case it cannot be done for all required store paths at once, and is therefore much slower than otherwise.

Realising store objects during evaluation can be disabled by setting allow-import-from-derivation to false. Without IFD it is ensured that evaluation is complete and Nix can produce a build plan before starting any realisation.

Example

In the following Nix expression, the inner derivation drv produces a file with contents hello.

# IFD.nix
let
  drv = derivation {
    name = "hello";
    builder = "/bin/sh";
    args = [ "-c" "echo -n hello > $out" ];
    system = builtins.currentSystem;
  };
in "${builtins.readFile drv} world"
nix-instantiate IFD.nix --eval --read-write-mode
building '/nix/store/348q1cal6sdgfxs8zqi9v8llrsn4kqkq-hello.drv'...
"hello world"

The contents of the derivation's output have to be realised before they can be read with readFile. Only then evaluation can continue to produce the final result.

Illustration

As a first approximation, the following data flow graph shows how evaluation and building are interleaved, if the value of a Nix expression depends on realising a store object. Boxes are data structures, arrow labels are transformations.

+----------------------+             +------------------------+
| Nix evaluator        |             | Nix store              |
|  .----------------.  |             |                        |
|  | Nix expression |  |             |                        |
|  '----------------'  |             |                        |
|          |           |             |                        |
|       evaluate       |             |                        |
|          |           |             |                        |
|          V           |             |                        |
|    .------------.    |             |                        |
|    | derivation |    |             |  .------------------.  |
|    | expression |----|-instantiate-|->| store derivation |  |
|    '------------'    |             |  '------------------'  |
|                      |             |           |            |
|                      |             |        realise         |
|                      |             |           |            |
|                      |             |           V            |
|  .----------------.  |             |    .--------------.    |
|  | Nix expression |<-|----read-----|----| store object |    |
|  '----------------'  |             |    '--------------'    |
|          |           |             |                        |
|       evaluate       |             |                        |
|          |           |             |                        |
|          V           |             |                        |
|    .------------.    |             |                        |
|    |   value    |    |             |                        |
|    '------------'    |             |                        |
+----------------------+             +------------------------+

In more detail, the following sequence diagram shows how the expression is evaluated step by step, and where evaluation is blocked to wait for the build output to appear.

.-------.     .-------------.                        .---------.
|Nix CLI|     |Nix evaluator|                        |Nix store|
'-------'     '-------------'                        '---------'
    |                |                                    |
    |evaluate IFD.nix|                                    |
    |--------------->|                                    |
    |                |                                    |
    |  evaluate `"${readFile drv} world"`                 |
    |                |                                    |
    |    evaluate `readFile drv`                          |
    |                |                                    |
    |   evaluate `drv` as string                          |
    |                |                                    |
    |                |instantiate /nix/store/...-hello.drv|
    |                |----------------------------------->|
    |                :                                    |
    |                :  realise /nix/store/...-hello.drv  |
    |                :----------------------------------->|
    |                :                                    |
    |                                                     |--------.
    |                :                                    |        |
    |      (evaluation blocked)                           |  echo hello > $out
    |                :                                    |        |
    |                                                     |<-------'
    |                :        /nix/store/...-hello        |
    |                |<-----------------------------------|
    |                |                                    |
    |  resume `readFile /nix/store/...-hello`             |
    |                |                                    |
    |                |   readFile /nix/store/...-hello    |
    |                |----------------------------------->|
    |                |                                    |
    |                |               hello                |
    |                |<-----------------------------------|
    |                |                                    |
    |      resume `"${"hello"} world"`                    |
    |                |                                    |
    |        resume `"hello world"`                       |
    |                |                                    |
    | "hello world"  |                                    |
    |<---------------|                                    |
.-------.     .-------------.                        .---------.
|Nix CLI|     |Nix evaluator|                        |Nix store|
'-------'     '-------------'                        '---------'

This chapter discusses how to do package management with Nix, i.e., how to obtain, install, upgrade, and erase packages. This is the “user’s” perspective of the Nix system — people who want to create packages should consult the chapter on the Nix language.

Profiles

Profiles and user environments are Nix’s mechanism for implementing the ability to allow different users to have different configurations, and to do atomic upgrades and rollbacks. To understand how they work, it’s useful to know a bit about how Nix works. In Nix, packages are stored in unique locations in the Nix store (typically, /nix/store). For instance, a particular version of the Subversion package might be stored in a directory /nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3/, while another version might be stored in /nix/store/5mq2jcn36ldlmh93yj1n8s9c95pj7c5s-subversion-1.1.2. The long strings prefixed to the directory names are cryptographic hashes (to be precise, 160-bit truncations of SHA-256 hashes encoded in a base-32 notation) of all inputs involved in building the package — sources, dependencies, compiler flags, and so on. So if two packages differ in any way, they end up in different locations in the file system, so they don’t interfere with each other. Here is what a part of a typical Nix store looks like:

Of course, you wouldn’t want to type

$ /nix/store/dpmvp969yhdq...-subversion-1.1.3/bin/svn

every time you want to run Subversion. Of course we could set up the PATH environment variable to include the bin directory of every package we want to use, but this is not very convenient since changing PATH doesn’t take effect for already existing processes. The solution Nix uses is to create directory trees of symlinks to activated packages. These are called user environments and they are packages themselves (though automatically generated by nix-env), so they too reside in the Nix store. For instance, in the figure above, the user environment /nix/store/0c1p5z4kda11...-user-env contains a symlink to just Subversion 1.1.2 (arrows in the figure indicate symlinks). This would be what we would obtain if we had done

$ nix-env --install --attr nixpkgs.subversion

on a set of Nix expressions that contained Subversion 1.1.2.

This doesn’t in itself solve the problem, of course; you wouldn’t want to type /nix/store/0c1p5z4kda11...-user-env/bin/svn either. That’s why there are symlinks outside of the store that point to the user environments in the store; for instance, the symlinks default-42-link and default-43-link in the example. These are called generations since every time you perform a nix-env operation, a new user environment is generated based on the current one. For instance, generation 43 was created from generation 42 when we did

$ nix-env --install --attr nixpkgs.subversion nixpkgs.firefox

on a set of Nix expressions that contained Firefox and a new version of Subversion.

Generations are grouped together into profiles so that different users don’t interfere with each other if they don’t want to. For example:

$ ls -l /nix/var/nix/profiles/
...
lrwxrwxrwx  1 eelco ... default-42-link -> /nix/store/0c1p5z4kda11...-user-env
lrwxrwxrwx  1 eelco ... default-43-link -> /nix/store/3aw2pdyx2jfc...-user-env
lrwxrwxrwx  1 eelco ... default -> default-43-link

This shows a profile called default. The file default itself is actually a symlink that points to the current generation. When we do a nix-env operation, a new user environment and generation link are created based on the current one, and finally the default symlink is made to point at the new generation. This last step is atomic on Unix, which explains how we can do atomic upgrades. (Note that the building/installing of new packages doesn’t interfere in any way with old packages, since they are stored in different locations in the Nix store.)

If you find that you want to undo a nix-env operation, you can just do

$ nix-env --rollback

which will just make the current generation link point at the previous link. E.g., default would be made to point at default-42-link. You can also switch to a specific generation:

$ nix-env --switch-generation 43

which in this example would roll forward to generation 43 again. You can also see all available generations:

$ nix-env --list-generations

You generally wouldn’t have /nix/var/nix/profiles/some-profile/bin in your PATH. Rather, there is a symlink ~/.nix-profile that points to your current profile. This means that you should put ~/.nix-profile/bin in your PATH (and indeed, that’s what the initialisation script /nix/etc/profile.d/nix.sh does). This makes it easier to switch to a different profile. You can do that using the command nix-env --switch-profile:

$ nix-env --switch-profile /nix/var/nix/profiles/my-profile

$ nix-env --switch-profile /nix/var/nix/profiles/default

These commands switch to the my-profile and default profile, respectively. If the profile doesn’t exist, it will be created automatically. You should be careful about storing a profile in another location than the profiles directory, since otherwise it might not be used as a root of the garbage collector.

All nix-env operations work on the profile pointed to by ~/.nix-profile, but you can override this using the --profile option (abbreviation -p):

$ nix-env --profile /nix/var/nix/profiles/other-profile --install --attr nixpkgs.subversion

This will not change the ~/.nix-profile symlink.

Garbage Collection

nix-env operations such as upgrades (-u) and uninstall (-e) never actually delete packages from the system. All they do (as shown above) is to create a new user environment that no longer contains symlinks to the “deleted” packages.

Of course, since disk space is not infinite, unused packages should be removed at some point. You can do this by running the Nix garbage collector. It will remove from the Nix store any package not used (directly or indirectly) by any generation of any profile.

Note however that as long as old generations reference a package, it will not be deleted. After all, we wouldn’t be able to do a rollback otherwise. So in order for garbage collection to be effective, you should also delete (some) old generations. Of course, this should only be done if you are certain that you will not need to roll back.

To delete all old (non-current) generations of your current profile:

$ nix-env --delete-generations old

Instead of old you can also specify a list of generations, e.g.,

$ nix-env --delete-generations 10 11 14

To delete all generations older than a specified number of days (except the current generation), use the d suffix. For example,

$ nix-env --delete-generations 14d

deletes all generations older than two weeks.

After removing appropriate old generations you can run the garbage collector as follows:

$ nix-store --gc

The behaviour of the garbage collector is affected by the keep-derivations (default: true) and keep-outputs (default: false) options in the Nix configuration file. The defaults will ensure that all derivations that are build-time dependencies of garbage collector roots will be kept and that all output paths that are runtime dependencies will be kept as well. All other derivations or paths will be collected. (This is usually what you want, but while you are developing it may make sense to keep outputs to ensure that rebuild times are quick.) If you are feeling uncertain, you can also first view what files would be deleted:

$ nix-store --gc --print-dead

Likewise, the option --print-live will show the paths that won’t be deleted.

There is also a convenient little utility nix-collect-garbage, which when invoked with the -d (--delete-old) switch deletes all old generations of all profiles in /nix/var/nix/profiles. So

$ nix-collect-garbage -d

is a quick and easy way to clean up your system.

Garbage Collector Roots

The roots of the garbage collector are all store paths to which there are symlinks in the directory prefix/nix/var/nix/gcroots. For instance, the following command makes the path /nix/store/d718ef...-foo a root of the collector:

$ ln -s /nix/store/d718ef...-foo /nix/var/nix/gcroots/bar

That is, after this command, the garbage collector will not remove /nix/store/d718ef...-foo or any of its dependencies.

Subdirectories of prefix/nix/var/nix/gcroots are also searched for symlinks. Symlinks to non-store paths are followed and searched for roots, but symlinks to non-store paths inside the paths reached in that way are not followed to prevent infinite recursion.

This section lists advanced topics related to builds and builds performance

Sharing Packages Between Machines

Sometimes you want to copy a package from one machine to another. Or, you want to install some packages and you know that another machine already has some or all of those packages or their dependencies. In that case there are mechanisms to quickly copy packages between machines.

Serving a Nix store via HTTP

You can easily share the Nix store of a machine via HTTP. This allows other machines to fetch store paths from that machine to speed up installations. It uses the same binary cache mechanism that Nix usually uses to fetch pre-built binaries from https://cache.nixos.org.

The daemon that handles binary cache requests via HTTP, nix-serve, is not part of the Nix distribution, but you can install it from Nixpkgs:

$ nix-env --install --attr nixpkgs.nix-serve

You can then start the server, listening for HTTP connections on whatever port you like:

$ nix-serve -p 8080

To check whether it works, try the following on the client:

$ curl http://avalon:8080/nix-cache-info

which should print something like:

StoreDir: /nix/store
WantMassQuery: 1
Priority: 30

On the client side, you can tell Nix to use your binary cache using --substituters, e.g.:

$ nix-env --install --attr nixpkgs.firefox --substituters http://avalon:8080/

The option substituters tells Nix to use this binary cache in addition to your default caches, such as https://cache.nixos.org. Thus, for any path in the closure of Firefox, Nix will first check if the path is available on the server avalon or another binary caches. If not, it will fall back to building from source.

You can also tell Nix to always use your binary cache by adding a line to the nix.conf configuration file like this:

substituters = http://avalon:8080/ https://cache.nixos.org/

Serving a Nix store via SSH

You can tell Nix to automatically fetch needed binaries from a remote Nix store via SSH. For example, the following installs Firefox, automatically fetching any store paths in Firefox’s closure if they are available on the server avalon:

$ nix-env --install --attr nixpkgs.firefox --substituters ssh://alice@avalon

This works similar to the binary cache substituter that Nix usually uses, only using SSH instead of HTTP: if a store path P is needed, Nix will first check if it’s available in the Nix store on avalon. If not, it will fall back to using the binary cache substituter, and then to building from source.

Note

The SSH substituter currently does not allow you to enter an SSH passphrase interactively. Therefore, you should use ssh-add to load the decrypted private key into ssh-agent.

You can also copy the closure of some store path, without installing it into your profile, e.g.

$ nix-store --realise /nix/store/m85bxg…-firefox-34.0.5 --substituters
ssh://alice@avalon

This is essentially equivalent to doing

$ nix-copy-closure --from alice@avalon
/nix/store/m85bxg…-firefox-34.0.5

You can use SSH’s forced command feature to set up a restricted user account for SSH substituter access, allowing read-only access to the local Nix store, but nothing more. For example, add the following lines to sshd_config to restrict the user nix-ssh:

Match User nix-ssh
  AllowAgentForwarding no
  AllowTcpForwarding no
  PermitTTY no
  PermitTunnel no
  X11Forwarding no
  ForceCommand nix-store --serve
Match All

On NixOS, you can accomplish the same by adding the following to your configuration.nix:

nix.sshServe.enable = true;
nix.sshServe.keys = [ "ssh-dss AAAAB3NzaC1k... bob@example.org" ];

where the latter line lists the public keys of users that are allowed to connect.

Remote Builds

A local Nix installation can forward Nix builds to other machines, this allows multiple builds to be performed in parallel.

Remote builds also allow Nix to perform multi-platform builds in a semi-transparent way. For example, if you perform a build for a x86_64-darwin on an i686-linux machine, Nix can automatically forward the build to a x86_64-darwin machine, if one is available.

Requirements

For a local machine to forward a build to a remote machine, the remote machine must:

  • Have Nix installed
  • Be running an SSH server, e.g. sshd
  • Be accessible via SSH from the local machine over the network
  • Have the local machine's public SSH key in /etc/ssh/authorized_keys.d/<username>
  • Have the username of the SSH user in the trusted-users setting in nix.conf

Testing

To test connecting to a remote Nix instance (in this case mac), run:

nix store info --store ssh://username@mac

To specify an SSH identity file as part of the remote store URI add a query paramater, e.g.

nix store info --store ssh://username@mac?ssh-key=/home/alice/my-key

Since builds should be non-interactive, the key should not have a passphrase. Alternatively, you can load identities ahead of time into ssh-agent or gpg-agent.

In a multi-user installation (default), builds are executed by the Nix Daemon. The Nix Daemon cannot prompt for a passphrase via the terminal or ssh-agent, so the SSH key must not have a passphrase.

In addition, the Nix Daemon's user (typically root) needs to have SSH access to the remote builder.

Access can be verified by running sudo su, and then validating SSH access, e.g. by running ssh mac. SSH identity files for root users are usually stored in /root/.ssh/ (Linux) or /var/root/.ssh (MacOS).

If you get the error

bash: nix: command not found
error: cannot connect to 'mac'

then you need to ensure that the PATH of non-interactive login shells contains Nix.

The list of remote build machines can be specified on the command line or in the Nix configuration file. For example, the following command allows you to build a derivation for x86_64-darwin on a Linux machine:

uname
Linux
nix build --impure \
 --expr '(with import <nixpkgs> { system = "x86_64-darwin"; }; runCommand "foo" {} "uname > $out")' \
 --builders 'ssh://mac x86_64-darwin'
[1/0/1 built, 0.0 MiB DL] building foo on ssh://mac
cat ./result
Darwin

It is possible to specify multiple build machines separated by a semicolon or a newline, e.g.

  --builders 'ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd'

Remote build machines can also be configured in nix.conf, e.g.

builders = ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd

After making changes to nix.conf, restart the Nix daemon for changes to take effect.

Finally, remote build machines can be configured in a separate configuration file included in builders via the syntax @/path/to/file. For example,

builders = @/etc/nix/machines

causes the list of machines in /etc/nix/machines to be included. (This is the default.)

Tuning Cores and Jobs

Nix has two relevant settings with regards to how your CPU cores will be utilized: cores and max-jobs. This chapter will talk about what they are, how they interact, and their configuration trade-offs.

  • max-jobs
    Dictates how many separate derivations will be built at the same time. If you set this to zero, the local machine will do no builds. Nix will still substitute from binary caches, and build remotely if remote builders are configured.

  • cores
    Suggests how many cores each derivation should use. Similar to make -j.

The cores setting determines the value of NIX_BUILD_CORES. NIX_BUILD_CORES is equal to cores, unless cores equals 0, in which case NIX_BUILD_CORES will be the total number of cores in the system.

The maximum number of consumed cores is a simple multiplication, max-jobs * NIX_BUILD_CORES.

The balance on how to set these two independent variables depends upon each builder's workload and hardware. Here are a few example scenarios on a machine with 24 cores:

max-jobscoresNIX_BUILD_CORESMaximum ProcessesResult
1242424One derivation will be built at a time, each one can use 24 cores. Undersold if a job can’t use 24 cores.
46624Four derivations will be built at once, each given access to six cores.
12667212 derivations will be built at once, each given access to six cores. This configuration is over-sold. If all 12 derivations being built simultaneously try to use all six cores, the machine's performance will be degraded due to extensive context switching between the 12 builds.
24112424 derivations can build at the same time, each using a single core. Never oversold, but derivations which require many cores will be very slow to compile.
2402457624 derivations can build at the same time, each using all the available cores of the machine. Very likely to be oversold, and very likely to suffer context switches.

It is up to the derivations' build script to respect host's requested cores-per-build by following the value of the NIX_BUILD_CORES environment variable.

Verifying Build Reproducibility

You can use Nix's diff-hook setting to compare build results. Note that this hook is only executed if the results differ; it is not used for determining if the results are the same.

For purposes of demonstration, we'll use the following Nix file, deterministic.nix for testing:

let
  inherit (import <nixpkgs> {}) runCommand;
in {
  stable = runCommand "stable" {} ''
    touch $out
  '';

  unstable = runCommand "unstable" {} ''
    echo $RANDOM > $out
  '';
}

Additionally, nix.conf contains:

diff-hook = /etc/nix/my-diff-hook
run-diff-hook = true

where /etc/nix/my-diff-hook is an executable file containing:

#!/bin/sh
exec >&2
echo "For derivation $3:"
/run/current-system/sw/bin/diff -r "$1" "$2"

The diff hook is executed by the same user and group who ran the build. However, the diff hook does not have write access to the store path just built.

Spot-Checking Build Determinism

Verify a path which already exists in the Nix store by passing --check to the build command.

If the build passes and is deterministic, Nix will exit with a status code of 0:

$ nix-build ./deterministic.nix --attr stable
this derivation will be built:
  /nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv
building '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable

$ nix-build ./deterministic.nix --attr stable --check
checking outputs of '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable

If the build is not deterministic, Nix will exit with a status code of 1:

$ nix-build ./deterministic.nix --attr unstable
this derivation will be built:
  /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv
building '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable

$ nix-build ./deterministic.nix --attr unstable --check
checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
error: derivation '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv' may
not be deterministic: output '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable' differs

In the Nix daemon's log, we will now see:

For derivation /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv:
1c1
< 8108
---
> 30204

Using --check with --keep-failed will cause Nix to keep the second build's output in a special, .check path:

$ nix-build ./deterministic.nix --attr unstable --check --keep-failed
checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
note: keeping build directory '/tmp/nix-build-unstable.drv-0'
error: derivation '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv' may
not be deterministic: output '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable' differs
from '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check'

In particular, notice the /nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check output. Nix has copied the build results to that directory where you can examine it.

Note

Check paths are not protected against garbage collection, and this path will be deleted on the next garbage collection.

The path is guaranteed to be alive for the duration of the diff-hook's execution, but may be deleted any time after.

If the comparison is performed as part of automated tooling, please use the diff-hook or author your tooling to handle the case where the build was not deterministic and also a check path does not exist.

--check is only usable if the derivation has been built on the system already. If the derivation has not been built Nix will fail with the error:

error: some outputs of '/nix/store/hzi1h60z2qf0nb85iwnpvrai3j2w7rr6-unstable.drv' 
are not valid, so checking is not possible

Run the build without --check, and then try with --check again.

Using the post-build-hook

Implementation Caveats

Here we use the post-build hook to upload to a binary cache. This is a simple and working example, but it is not suitable for all use cases.

The post build hook program runs after each executed build, and blocks the build loop. The build loop exits if the hook program fails.

Concretely, this implementation will make Nix slow or unusable when the internet is slow or unreliable.

A more advanced implementation might pass the store paths to a user-supplied daemon or queue for processing the store paths outside of the build loop.

Prerequisites

This tutorial assumes you have configured an S3-compatible binary cache as a substituter, and that the root user's default AWS profile can upload to the bucket.

Set up a Signing Key

Use nix-store --generate-binary-cache-key to create our public and private signing keys. We will sign paths with the private key, and distribute the public key for verifying the authenticity of the paths.

# nix-store --generate-binary-cache-key example-nix-cache-1 /etc/nix/key.private /etc/nix/key.public
# cat /etc/nix/key.public
example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM=

Then update nix.conf on any machine that will access the cache. Add the cache URL to substituters and the public key to trusted-public-keys:

substituters = https://cache.nixos.org/ s3://example-nix-cache
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM=

Machines that build for the cache must sign derivations using the private key. On those machines, add the path to the key file to the secret-key-files field in their nix.conf:

secret-key-files = /etc/nix/key.private

We will restart the Nix daemon in a later step.

Implementing the build hook

Write the following script to /etc/nix/upload-to-cache.sh:

#!/bin/sh

set -eu
set -f # disable globbing
export IFS=' '

echo "Uploading paths" $OUT_PATHS
exec nix copy --to "s3://example-nix-cache" $OUT_PATHS

Note

The $OUT_PATHS variable is a space-separated list of Nix store paths. In this case, we expect and want the shell to perform word splitting to make each output path its own argument to nix store sign. Nix guarantees the paths will not contain any spaces, however a store path might contain glob characters. The set -f disables globbing in the shell. If you want to upload the .drv file too, the $DRV_PATH variable is also defined for the script and works just like $OUT_PATHS.

Then make sure the hook program is executable by the root user:

# chmod +x /etc/nix/upload-to-cache.sh

Updating Nix Configuration

Edit /etc/nix/nix.conf to run our hook, by adding the following configuration snippet at the end:

post-build-hook = /etc/nix/upload-to-cache.sh

Then, restart the nix-daemon.

Testing

Build any derivation, for example:

$ nix-build --expr '(import <nixpkgs> {}).writeText "example" (builtins.toString builtins.currentTime)'
this derivation will be built:
  /nix/store/s4pnfbkalzy5qz57qs6yybna8wylkig6-example.drv
building '/nix/store/s4pnfbkalzy5qz57qs6yybna8wylkig6-example.drv'...
running post-build-hook '/home/grahamc/projects/github.com/NixOS/nix/post-hook.sh'...
post-build-hook: Signing paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
post-build-hook: Uploading paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
/nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example

Then delete the path from the store, and try substituting it from the binary cache:

$ rm ./result
$ nix-store --delete /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example

Now, copy the path back from the cache:

$ nix-store --realise /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
copying path '/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example from 's3://example-nix-cache'...
warning: you did not specify '--add-root'; the result might be removed by the garbage collector
/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example

Conclusion

We now have a Nix installation configured to automatically sign and upload every local build to a remote binary cache.

Before deploying this to production, be sure to consider the implementation caveats.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Subcommands

This section lists all the subcommands of the nix CLI.

Name

nix - a tool for reproducible and declarative configuration management

Synopsis

nix [option...] subcommand

where subcommand is one of the following:

Help commands:

  • nix help - show help about nix or a particular subcommand
  • nix help-stores - show help about store types and their settings

Main commands:

  • nix build - build a derivation or fetch a store path
  • nix develop - run a bash shell that provides the build environment of a derivation
  • nix flake - manage Nix flakes
  • nix profile - manage Nix profiles
  • nix repl - start an interactive environment for evaluating Nix expressions
  • nix run - run a Nix application
  • nix search - search for packages

Infrequently used commands:

  • nix bundle - bundle an application so that it works outside of the Nix store
  • nix copy - copy paths between Nix stores
  • nix edit - open the Nix expression of a Nix package in $EDITOR
  • nix eval - evaluate a Nix expression
  • nix fmt - reformat your code in the standard style
  • nix log - show the build log of the specified packages or paths, if available
  • nix path-info - query information about store paths
  • nix registry - manage the flake registry
  • nix why-depends - show why a package has another package in its closure

Utility/scripting commands:

  • nix config - manipulate the Nix configuration
  • nix daemon - daemon to perform store operations on behalf of non-root clients
  • nix derivation - Work with derivations, Nix's notion of a build plan.
  • nix env - manipulate the process environment
  • nix hash - compute and convert cryptographic hashes
  • nix key - generate and convert Nix signing keys
  • nix nar - create or inspect NAR files
  • nix print-dev-env - print shell code that can be sourced by bash to reproduce the build environment of a derivation
  • nix realisation - manipulate a Nix realisation
  • nix store - manipulate a Nix store

Commands for upgrading or troubleshooting your Nix installation:

Examples

  • Create a new flake:

    # nix flake new hello
    # cd hello
    
  • Build the flake in the current directory:

    # nix build
    # ./result/bin/hello
    Hello, world!
    
  • Run the flake in the current directory:

    # nix run
    Hello, world!
    
  • Start a development shell for hacking on this flake:

    # nix develop
    # unpackPhase
    # cd hello-*
    # configurePhase
    # buildPhase
    # ./hello
    Hello, world!
    # installPhase
    # ../outputs/out/bin/hello
    Hello, world!
    

Description

Nix is a tool for building software, configurations and other artifacts in a reproducible and declarative way. For more information, see the Nix homepage or the Nix manual.

Installables

Many nix subcommands operate on one or more installables. These are command line arguments that represent something that can be realised in the Nix store.

The following types of installable are supported by most commands:

  • Flake output attribute (experimental)
    • This is the default
  • Store path
    • This is assumed if the argument is a Nix store path or a symlink to a Nix store path
  • Nix file, optionally qualified by an attribute path
    • Specified with --file/-f
  • Nix expression, optionally qualified by an attribute path
    • Specified with --expr

For most commands, if no installable is specified, . is assumed. That is, Nix will operate on the default flake output attribute of the flake in the current directory.

Flake output attribute

Example: nixpkgs#hello

These have the form flakeref[#attrpath], where flakeref is a flake reference and attrpath is an optional attribute path. For more information on flakes, see the nix flake manual page. Flake references are most commonly a flake identifier in the flake registry (e.g. nixpkgs), or a raw path (e.g. /path/to/my-flake or . or ../foo), or a full URL (e.g. github:nixos/nixpkgs or path:.)

When the flake reference is a raw path (a path without any URL scheme), it is interpreted as a path: or git+file: url in the following way:

  • If the path is within a Git repository, then the url will be of the form git+file://[GIT_REPO_ROOT]?dir=[RELATIVE_FLAKE_DIR_PATH] where GIT_REPO_ROOT is the path to the root of the git repository, and RELATIVE_FLAKE_DIR_PATH is the path (relative to the directory root) of the closest parent of the given path that contains a flake.nix within the git repository. If no such directory exists, then Nix will error-out.

    Note that the search will only include files indexed by git. In particular, files which are matched by .gitignore or have never been git add-ed will not be available in the flake. If this is undesirable, specify path:<directory> explicitly;

    For example, if /foo/bar is a git repository with the following structure:

    .
    └── baz
        ├── blah
        │   └── file.txt
        └── flake.nix
    

    Then /foo/bar/baz/blah will resolve to git+file:///foo/bar?dir=baz

  • If the supplied path is not a git repository, then the url will have the form path:FLAKE_DIR_PATH where FLAKE_DIR_PATH is the closest parent of the supplied path that contains a flake.nix file (within the same file-system). If no such directory exists, then Nix will error-out.

    For example, if /foo/bar/flake.nix exists, then /foo/bar/baz/ will resolve to path:/foo/bar

If attrpath is omitted, Nix tries some default values; for most subcommands, the default is packages.system.default (e.g. packages.x86_64-linux.default), but some subcommands have other defaults. If attrpath is specified, attrpath is interpreted as relative to one or more prefixes; for most subcommands, these are packages.system, legacyPackages.*system* and the empty prefix. Thus, on x86_64-linux nix build nixpkgs#hello will try to build the attributes packages.x86_64-linux.hello, legacyPackages.x86_64-linux.hello and hello.

If attrpath begins with . then no prefixes or defaults are attempted. This allows the form flakeref[#.attrpath], such as github:NixOS/nixpkgs#.lib.fakeSha256 to avoid a search of packages.*system*.lib.fakeSha256

Store path

Example: /nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10

These are paths inside the Nix store, or symlinks that resolve to a path in the Nix store.

A store derivation is also addressed by store path.

Example: /nix/store/p7gp6lxdg32h4ka1q398wd9r2zkbbz2v-hello-2.10.drv

If you want to refer to an output path of that store derivation, add the output name preceded by a caret (^).

Example: /nix/store/p7gp6lxdg32h4ka1q398wd9r2zkbbz2v-hello-2.10.drv^out

All outputs can be referred to at once with the special syntax ^*.

Example: /nix/store/p7gp6lxdg32h4ka1q398wd9r2zkbbz2v-hello-2.10.drv^*

Nix file

Example: --file /path/to/nixpkgs hello

When the option -f / --file path [attrpath...] is given, installables are interpreted as the value of the expression in the Nix file at path. If attribute paths are provided, commands will operate on the corresponding values accessible at these paths. The Nix expression in that file, or any selected attribute, must evaluate to a derivation.

Nix expression

Example: --expr 'import <nixpkgs> {}' hello

When the option --expr expression [attrpath...] is given, installables are interpreted as the value of the of the Nix expression. If attribute paths are provided, commands will operate on the corresponding values accessible at these paths. The Nix expression, or any selected attribute, must evaluate to a derivation.

You may need to specify --impure if the expression references impure inputs (such as <nixpkgs>).

Derivation output selection

Derivations can have multiple outputs, each corresponding to a different store path. For instance, a package can have a bin output that contains programs, and a dev output that provides development artifacts like C/C++ header files. The outputs on which nix commands operate are determined as follows:

  • You can explicitly specify the desired outputs using the syntax installable^output1,...,outputN — that is, a caret followed immediately by a comma-separated list of derivation outputs to select. For installables specified as Flake output attributes or Store paths, the output is specified in the same argument:

    For example, you can obtain the dev and static outputs of the glibc package:

    # nix build 'nixpkgs#glibc^dev,static'
    # ls ./result-dev/include/ ./result-static/lib/
    …
    

    and likewise, using a store path to a "drv" file to specify the derivation:

    # nix build '/nix/store/gzaflydcr6sb3567hap9q6srzx8ggdgg-glibc-2.33-78.drv^dev,static'
    …
    

    For --expr and -f/--file, the derivation output is specified as part of the attribute path:

    $ nix build -f '<nixpkgs>' 'glibc^dev,static'
    $ nix build --impure --expr 'import <nixpkgs> { }' 'glibc^dev,static'
    

    This syntax is the same even if the actual attribute path is empty:

    $ nix build --impure --expr 'let pkgs = import <nixpkgs> { }; in pkgs.glibc' '^dev,static'
    
  • You can also specify that all outputs should be used using the syntax installable^*. For example, the following shows the size of all outputs of the glibc package in the binary cache:

    # nix path-info --closure-size --eval-store auto --store https://cache.nixos.org 'nixpkgs#glibc^*'
    /nix/store/g02b1lpbddhymmcjb923kf0l7s9nww58-glibc-2.33-123                 33208200
    /nix/store/851dp95qqiisjifi639r0zzg5l465ny4-glibc-2.33-123-bin             36142896
    /nix/store/kdgs3q6r7xdff1p7a9hnjr43xw2404z7-glibc-2.33-123-debug          155787312
    /nix/store/n4xa8h6pbmqmwnq0mmsz08l38abb06zc-glibc-2.33-123-static          42488328
    /nix/store/q6580lr01jpcsqs4r5arlh4ki2c1m9rv-glibc-2.33-123-dev             44200560
    

    and likewise, using a store path to a "drv" file to specify the derivation:

    # nix path-info --closure-size '/nix/store/gzaflydcr6sb3567hap9q6srzx8ggdgg-glibc-2.33-78.drv^*'
    …
    
  • If you didn't specify the desired outputs, but the derivation has an attribute meta.outputsToInstall, Nix will use those outputs. For example, since the package nixpkgs#libxml2 has this attribute:

    # nix eval 'nixpkgs#libxml2.meta.outputsToInstall'
    [ "bin" "man" ]
    

    a command like nix shell nixpkgs#libxml2 will provide only those two outputs by default.

    Note that a store derivation (given by its .drv file store path) doesn't have any attributes like meta, and thus this case doesn't apply to it.

  • Otherwise, Nix will use all outputs of the derivation.

Nix stores

Most nix subcommands operate on a Nix store. The various store types are documented in the Store Types section of the manual.

The same information is also available from the nix help-stores command.

Shebang interpreter

The nix command can be used as a #! interpreter. Arguments to Nix can be passed on subsequent lines in the script.

Verbatim strings may be passed in double backtick (``) quotes. Sequences of n backticks of 3 or longer are parsed as n-1 literal backticks. A single space before the closing `` is ignored if present.

--file and --expr resolve relative paths based on the script location.

Examples:

#!/usr/bin/env nix
#! nix shell --file ``<nixpkgs>`` hello cowsay --command bash

hello | cowsay

or with flakes:

#!/usr/bin/env nix
#! nix shell nixpkgs#bash nixpkgs#hello nixpkgs#cowsay --command bash

hello | cowsay

or with an expression:

#! /usr/bin/env nix
#! nix shell --impure --expr ``
#! nix with (import (builtins.getFlake "nixpkgs") {});
#! nix terraform.withPlugins (plugins: [ plugins.openstack ])
#! nix ``
#! nix --command bash

terraform "$@"

or with cascading interpreters. Note that the #! nix lines don't need to follow after the first line, to accommodate other interpreters.

#!/usr/bin/env nix
//! ```cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
/*
#!nix shell nixpkgs#rustc nixpkgs#rust-script nixpkgs#cargo --command rust-script
*/
fn main() {
    for argument in std::env::args().skip(1) {
        println!("{}", argument);
    };
    println!("{}", std::env::var("HOME").expect(""));
    println!("{}", time::now().rfc822z());
}
// vim: ft=rust

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix build - build a derivation or fetch a store path

Synopsis

nix build [option...] installables...

Examples

  • Build the default package from the flake in the current directory:

    # nix build
    
  • Build and run GNU Hello from the nixpkgs flake:

    # nix build nixpkgs#hello
    # ./result/bin/hello
    Hello, world!
    
  • Build GNU Hello and Cowsay, leaving two result symlinks:

    # nix build nixpkgs#hello nixpkgs#cowsay
    # ls -l result*
    lrwxrwxrwx 1 … result -> /nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10
    lrwxrwxrwx 1 … result-1 -> /nix/store/rkfrm0z6x6jmi7d3gsmma4j53h15mg33-cowsay-3.03+dfsg2
    
  • Build GNU Hello and print the resulting store path.

    # nix build nixpkgs#hello --print-out-paths
    /nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10
    
  • Build a specific output:

    # nix build nixpkgs#glibc.dev
    # ls -ld ./result-dev
    lrwxrwxrwx 1 … ./result-dev -> /nix/store/dkm3gwl0xrx0wrw6zi5x3px3lpgjhlw4-glibc-2.32-dev
    
  • Build all outputs:

    # nix build "nixpkgs#openssl^*" --print-out-paths
    /nix/store/gvad6v0cmq1qccmc4wphsazqbj0xzjsl-openssl-3.0.13-bin
    /nix/store/a07jqdrc8afnk8r6f3lnhh4gvab7chk4-openssl-3.0.13-debug
    /nix/store/yg75achq89wgqn2fi3gglgsd77kjpi03-openssl-3.0.13-dev
    /nix/store/bvdcihi8c88fw31cg6gzzmpnwglpn1jv-openssl-3.0.13-doc
    /nix/store/gjqcvq47cmxazxga0cirspm3jywkmvfv-openssl-3.0.13-man
    /nix/store/7nmrrad8skxr47f9hfl3xc0pfqmwq51b-openssl-3.0.13
    
  • Build attribute build.x86_64-linux from (non-flake) Nix expression release.nix:

    # nix build --file release.nix build.x86_64-linux
    
  • Build a NixOS system configuration from a flake, and make a profile point to the result:

    # nix build --profile /nix/var/nix/profiles/system \
        ~/my-configurations#nixosConfigurations.machine.config.system.build.toplevel
    

    (This is essentially what nixos-rebuild does.)

  • Build an expression specified on the command line:

    # nix build --impure --expr \
        'with import <nixpkgs> {};
         runCommand "foo" {
           buildInputs = [ hello ];
         }
         "hello > $out"'
    # cat ./result
    Hello, world!
    

    Note that --impure is needed because we're using <nixpkgs>, which relies on the $NIX_PATH environment variable.

  • Fetch a store path from the configured substituters, if it doesn't already exist:

    # nix build /nix/store/rkfrm0z6x6jmi7d3gsmma4j53h15mg33-cowsay-3.03+dfsg2
    

Description

nix build builds the specified installables. Installables that resolve to derivations are built (or substituted if possible). Store path installables are substituted.

Unless --no-link is specified, after a successful build, it creates symlinks to the store paths of the installables. These symlinks have the prefix ./result by default; this can be overridden using the --out-link option. Each symlink has a suffix -<N>-<outname>, where N is the index of the installable (with the left-most installable having index 0), and outname is the symbolic derivation output name (e.g. bin, dev or lib). -<N> is omitted if N = 0, and -<outname> is omitted if outname = out (denoting the default output).

Options

  • --dry-run

    Show what this command would do without doing it.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --no-link

    Do not create symlinks to the build results.

  • --out-link / -o path

    Use path as prefix for the symlinks to the build results. It defaults to result.

  • --print-out-paths

    Print the resulting output paths

  • --profile path

    The profile to operate on.

  • --rebuild

    Rebuild an already built package and compare the result to the existing store paths.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix bundle - bundle an application so that it works outside of the Nix store

Synopsis

nix bundle [option...] installable

Examples

  • Bundle Hello:

    # nix bundle nixpkgs#hello
    # ./hello
    Hello, world!
    
  • Bundle a specific version of Nix:

    # nix bundle github:NixOS/nix/e3ddffb27e5fc37a209cfd843c6f7f6a9460a8ec
    # ./nix --version
    nix (Nix) 2.4pre20201215_e3ddffb
    
  • Bundle a Hello using a specific bundler:

    # nix bundle --bundler github:NixOS/bundlers#toDockerImage nixpkgs#hello
    # docker load < hello-2.10.tar.gz
    # docker run hello-2.10:latest hello
    Hello, world!
    

Description

nix bundle, by default, packs the closure of the installable into a single self-extracting executable. See the bundlers homepage for more details.

Note

This command only works on Linux.

Flake output attributes

If no flake output attribute is given, nix bundle tries the following flake output attributes:

  • bundlers.<system>.default

If an attribute name is given, nix bundle tries the following flake output attributes:

  • bundlers.<system>.<name>

Bundlers

A bundler is specified by a flake output attribute named bundlers.<system>.<name>. It looks like this:

bundlers.x86_64-linux = rec {
  identity = drv: drv;

  blender_2_79 = drv: self.packages.x86_64-linux.blender_2_79;

  default = identity;
};

A bundler must be a function that accepts an arbitrary value (typically a derivation or app definition) and returns a derivation.

Options

  • --bundler flake-url

    Use a custom bundler instead of the default (github:NixOS/bundlers).

  • --out-link / -o path

    Override the name of the symlink to the build result. It defaults to the base name of the app.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix config - manipulate the Nix configuration

Synopsis

nix config [option...] subcommand

where subcommand is one of the following:

:

  • nix config show - show the Nix configuration or the value of a specific setting

:

  • nix config check - check your system for potential problems and print a PASS or FAIL for each check

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix config check - check your system for potential problems and print a PASS or FAIL for each check

Synopsis

nix config check [option...]

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix config show - show the Nix configuration or the value of a specific setting

Synopsis

nix config show [option...] name

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix copy - copy paths between Nix stores

Synopsis

nix copy [option...] installables...

Examples

  • Copy Firefox from the local store to a binary cache in /tmp/cache:

    # nix copy --to file:///tmp/cache $(type -p firefox)
    

    Note the file:// - without this, the destination is a chroot store, not a binary cache.

  • Copy all store paths from a local binary cache in /tmp/cache to the local store:

    # nix copy --all --from file:///tmp/cache
    
  • Copy the entire current NixOS system closure to another machine via SSH:

    # nix copy --substitute-on-destination --to ssh://server /run/current-system
    

    The -s flag causes the remote machine to try to substitute missing store paths, which may be faster if the link between the local and remote machines is slower than the link between the remote machine and its substituters (e.g. https://cache.nixos.org).

  • Copy a closure from another machine via SSH:

    # nix copy --from ssh://server /nix/store/a6cnl93nk1wxnq84brbbwr6hxw9gp2w9-blender-2.79-rc2
    
  • Copy Hello to a binary cache in an Amazon S3 bucket:

    # nix copy --to s3://my-bucket?region=eu-west-1 nixpkgs#hello
    

    or to an S3-compatible storage system:

    # nix copy --to s3://my-bucket?region=eu-west-1&endpoint=example.com nixpkgs#hello
    

    Note that this only works if Nix is built with AWS support.

  • Copy a closure from /nix/store to the chroot store /tmp/nix/nix/store:

    # nix copy --to /tmp/nix nixpkgs#hello --no-check-sigs
    
  • Update the NixOS system profile to point to a closure copied from a remote machine:

    # nix copy --from ssh://server \
        --profile /nix/var/nix/profiles/system \
        /nix/store/r14v3km89zm3prwsa521fab5kgzvfbw4-nixos-system-foobar-24.05.20240925.759537f
    

Description

nix copy copies store path closures between two Nix stores. The source store is specified using --from and the destination using --to. If one of these is omitted, it defaults to the local store.

Options

  • --from store-uri

    URL of the source Nix store.

  • --no-check-sigs

    Do not require that paths are signed by trusted keys.

  • --out-link / -o path

    Create symlinks prefixed with path to the top-level store paths fetched from the source store.

  • --profile path

    The profile to operate on.

  • --stdin

    Read installables from the standard input. No default installable applied.

  • --substitute-on-destination / -s

    Whether to try substitutes on the destination store (only supported by SSH stores).

  • --to store-uri

    URL of the destination Nix store.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --no-recursive

    Apply operation to specified paths only.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix daemon - daemon to perform store operations on behalf of non-root clients

Synopsis

nix daemon [option...]

Examples

  • Run the daemon:

    # nix daemon
    
  • Run the daemon and listen on standard I/O instead of binding to a UNIX socket:

    # nix daemon --stdio
    
  • Run the daemon and force all connections to be trusted:

    # nix daemon --force-trusted
    
  • Run the daemon and force all connections to be untrusted:

    # nix daemon --force-untrusted
    
  • Run the daemon, listen on standard I/O, and force all connections to use Nix's default trust:

    # nix daemon --stdio --default-trust
    

Description

This command runs the Nix daemon, which is a required component in multi-user Nix installations. It runs build tasks and other operations on the Nix store on behalf of non-root users. Usually you don't run the daemon directly; instead it's managed by a service management framework such as systemd on Linux, or launchctl on Darwin.

Note that this daemon does not fork into the background.

Options

  • --default-trust

    Use Nix's default trust.

  • --force-trusted

    Force the daemon to trust connecting clients.

  • --force-untrusted

    Force the daemon to not trust connecting clients. The connection will be processed by the receiving daemon before forwarding commands.

  • --process-ops

    Forces the daemon to process received commands itself rather than forwarding the commands straight to the remote store.

            This is useful for the `mounted-ssh://` store where some actions need to be performed on the remote end but as connected user, and not as the user of the underlying daemon on the remote end.
    
  • --stdio

    Attach to standard I/O, instead of trying to bind to a UNIX socket.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix derivation - Work with derivations, Nix's notion of a build plan.

Synopsis

nix derivation [option...] subcommand

where subcommand is one of the following:

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix derivation add - Add a store derivation

Synopsis

nix derivation add [option...]

Description

This command reads from standard input a JSON representation of a store derivation.

Store derivations are used internally by Nix. They are store paths with extension .drv that represent the build-time dependency graph to which a Nix expression evaluates.

nix derivation add takes a single derivation in the following format:

Derivation JSON Format

The JSON serialization of a derivations is a JSON object with the following fields:

  • name: The name of the derivation. This is used when calculating the store paths of the derivation's outputs.

  • outputs: Information about the output paths of the derivation. This is a JSON object with one member per output, where the key is the output name and the value is a JSON object with these fields:

    • path: The output path, if it is known in advanced. Otherwise, null.

    • method: For an output which will be [content addresed], a string representing the method of content addressing that is chosen. Valid method strings are:

      Otherwise, null.

    • hashAlgo: For an output which will be [content addresed], the name of the hash algorithm used. Valid algorithm strings are:

      • blake3
      • md5
      • sha1
      • sha256
      • sha512
    • hash: For fixed-output derivations, the expected content hash in base-16.

    Example

    "outputs": {
      "out": {
        "path": "/nix/store/2543j7c6jn75blc3drf4g5vhb1rhdq29-source",
        "method": "nar",
        "hashAlgo": "sha256",
        "hash": "6fc80dcc62179dbc12fc0b5881275898f93444833d21b89dfe5f7fbcbb1d0d62"
      }
    }
    
  • inputSrcs: A list of store paths on which this derivation depends.

  • inputDrvs: A JSON object specifying the derivations on which this derivation depends, and what outputs of those derivations.

    Example

    "inputDrvs": {
      "/nix/store/6lkh5yi7nlb7l6dr8fljlli5zfd9hq58-curl-7.73.0.drv": ["dev"],
      "/nix/store/fn3kgnfzl5dzym26j8g907gq3kbm8bfh-unzip-6.0.drv": ["out"]
    }
    

    specifies that this derivation depends on the dev output of curl, and the out output of unzip.

  • system: The system type on which this derivation is to be built (e.g. x86_64-linux).

  • builder: The absolute path of the program to be executed to run the build. Typically this is the bash shell (e.g. /nix/store/r3j288vpmczbl500w6zz89gyfa4nr0b1-bash-4.4-p23/bin/bash).

  • args: The command-line arguments passed to the builder.

  • env: The environment passed to the builder.

Options

  • --dry-run

    Show what this command would do without doing it.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix derivation show - show the contents of a store derivation

Synopsis

nix derivation show [option...] installables...

Examples

  • Show the store derivation that results from evaluating the Hello package:

    # nix derivation show nixpkgs#hello
    {
      "/nix/store/s6rn4jz1sin56rf4qj5b5v8jxjm32hlk-hello-2.10.drv": {
        …
      }
    }
    
  • Show the full derivation graph (if available) that produced your NixOS system:

    # nix derivation show -r /run/current-system
    
  • Print all files fetched using fetchurl by Firefox's dependency graph:

    # nix derivation show -r nixpkgs#firefox \
      | jq -r '.[] | select(.outputs.out.hash and .env.urls) | .env.urls' \
      | uniq | sort
    

    Note that .outputs.out.hash selects fixed-output derivations (derivations that produce output with a specified content hash), while .env.urls selects derivations with a urls attribute.

Description

This command prints on standard output a JSON representation of the store derivations to which installables evaluate.

Store derivations are used internally by Nix. They are store paths with extension .drv that represent the build-time dependency graph to which a Nix expression evaluates.

By default, this command only shows top-level derivations, but with --recursive, it also shows their dependencies.

nix derivation show outputs a JSON map of store paths to derivations in the following format:

Derivation JSON Format

The JSON serialization of a derivations is a JSON object with the following fields:

  • name: The name of the derivation. This is used when calculating the store paths of the derivation's outputs.

  • outputs: Information about the output paths of the derivation. This is a JSON object with one member per output, where the key is the output name and the value is a JSON object with these fields:

    • path: The output path, if it is known in advanced. Otherwise, null.

    • method: For an output which will be [content addresed], a string representing the method of content addressing that is chosen. Valid method strings are:

      Otherwise, null.

    • hashAlgo: For an output which will be [content addresed], the name of the hash algorithm used. Valid algorithm strings are:

      • blake3
      • md5
      • sha1
      • sha256
      • sha512
    • hash: For fixed-output derivations, the expected content hash in base-16.

    Example

    "outputs": {
      "out": {
        "path": "/nix/store/2543j7c6jn75blc3drf4g5vhb1rhdq29-source",
        "method": "nar",
        "hashAlgo": "sha256",
        "hash": "6fc80dcc62179dbc12fc0b5881275898f93444833d21b89dfe5f7fbcbb1d0d62"
      }
    }
    
  • inputSrcs: A list of store paths on which this derivation depends.

  • inputDrvs: A JSON object specifying the derivations on which this derivation depends, and what outputs of those derivations.

    Example

    "inputDrvs": {
      "/nix/store/6lkh5yi7nlb7l6dr8fljlli5zfd9hq58-curl-7.73.0.drv": ["dev"],
      "/nix/store/fn3kgnfzl5dzym26j8g907gq3kbm8bfh-unzip-6.0.drv": ["out"]
    }
    

    specifies that this derivation depends on the dev output of curl, and the out output of unzip.

  • system: The system type on which this derivation is to be built (e.g. x86_64-linux).

  • builder: The absolute path of the program to be executed to run the build. Typically this is the bash shell (e.g. /nix/store/r3j288vpmczbl500w6zz89gyfa4nr0b1-bash-4.4-p23/bin/bash).

  • args: The command-line arguments passed to the builder.

  • env: The environment passed to the builder.

Options

  • --recursive / -r

    Include the dependencies of the specified derivations.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix develop - run a bash shell that provides the build environment of a derivation

Synopsis

nix develop [option...] installable

Examples

  • Start a shell with the build environment of the default package of the flake in the current directory:

    # nix develop
    

    Typical commands to run inside this shell are:

    # configurePhase
    # buildPhase
    # installPhase
    

    Alternatively, you can run whatever build tools your project uses directly, e.g. for a typical Unix project:

    # ./configure --prefix=$out
    # make
    # make install
    
  • Run a particular build phase directly:

    # nix develop --unpack
    # nix develop --configure
    # nix develop --build
    # nix develop --check
    # nix develop --install
    # nix develop --installcheck
    
  • Start a shell with the build environment of GNU Hello:

    # nix develop nixpkgs#hello
    
  • Record a build environment in a profile:

    # nix develop --profile /tmp/my-build-env nixpkgs#hello
    
  • Use a build environment previously recorded in a profile:

    # nix develop /tmp/my-build-env
    
  • Replace all occurrences of the store path corresponding to glibc.dev with a writable directory:

    # nix develop --redirect nixpkgs#glibc.dev ~/my-glibc/outputs/dev
    

    Note that this is useful if you're running a nix develop shell for nixpkgs#glibc in ~/my-glibc and want to compile another package against it.

  • Run a series of script commands:

    # nix develop --command bash -c "mkdir build && cmake .. && make"
    

Description

nix develop starts a bash shell that provides an interactive build environment nearly identical to what Nix would use to build installable. Inside this shell, environment variables and shell functions are set up so that you can interactively and incrementally build your package.

Nix determines the build environment by building a modified version of the derivation installable that just records the environment initialised by stdenv and exits. This build environment can be recorded into a profile using --profile.

The prompt used by the bash shell can be customised by setting the bash-prompt, bash-prompt-prefix, and bash-prompt-suffix settings in nix.conf or in the flake's nixConfig attribute.

Flake output attributes

If no flake output attribute is given, nix develop tries the following flake output attributes:

  • devShells.<system>.default

  • packages.<system>.default

If a flake output name is given, nix develop tries the following flake output attributes:

  • devShells.<system>.<name>

  • packages.<system>.<name>

  • legacyPackages.<system>.<name>

Options

  • --build

    Run the build phase.

  • --check

    Run the check phase.

  • --command / -c command args

    Instead of starting an interactive shell, start the specified command and arguments.

  • --configure

    Run the configure phase.

  • --install

    Run the install phase.

  • --installcheck

    Run the installcheck phase.

  • --phase phase-name

    The stdenv phase to run (e.g. build or configure).

  • --profile path

    The profile to operate on.

  • --redirect installable outputs-dir

    Redirect a store path to a mutable location.

  • --unpack

    Run the unpack phase.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change environment variables

  • --ignore-env / -i

    Clear the entire environment, except for those specified with --keep-env-var.

  • --keep-env-var / -k name

    Keep the environment variable name, when using --ignore-env.

  • --set-env-var / -s name value

    Sets an environment variable name with value.

  • --unset-env-var / -u name

    Unset the environment variable name.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix edit - open the Nix expression of a Nix package in $EDITOR

Synopsis

nix edit [option...] installable

Examples

  • Open the Nix expression of the GNU Hello package:

    # nix edit nixpkgs#hello
    
  • Get the filename and line number used by nix edit:

    # nix eval --raw nixpkgs#hello.meta.position
    /nix/store/fvafw0gvwayzdan642wrv84pzm5bgpmy-source/pkgs/applications/misc/hello/default.nix:15
    

Description

This command opens the Nix expression of a derivation in an editor. The filename and line number of the derivation are taken from its meta.position attribute. Nixpkgs' stdenv.mkDerivation sets this attribute to the location of the definition of the meta.description, version or name derivation attributes.

The editor to invoke is specified by the EDITOR environment variable. It defaults to cat. If the editor is emacs, nano, vim or kak, it is passed the line number of the derivation using the argument +<lineno>.

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix env - manipulate the process environment

Synopsis

nix env [option...] subcommand

where subcommand is one of the following:

  • nix env shell - run a shell in which the specified packages are available

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix env shell - run a shell in which the specified packages are available

Synopsis

nix env shell [option...] installables...

Examples

  • Start a shell providing youtube-dl from the nixpkgs flake:

    # nix shell nixpkgs#youtube-dl
    # youtube-dl --version
    2020.11.01.1
    
  • Start a shell providing GNU Hello from NixOS 20.03:

    # nix shell nixpkgs/nixos-20.03#hello
    
  • Run GNU Hello:

    # nix shell nixpkgs#hello --command hello --greeting 'Hi everybody!'
    Hi everybody!
    
  • Run multiple commands in a shell environment:

    # nix shell nixpkgs#gnumake --command sh -c "cd src && make"
    
  • Run GNU Hello in a chroot store:

    # nix shell --store ~/my-nix nixpkgs#hello --command hello
    
  • Start a shell providing GNU Hello in a chroot store:

    # nix shell --store ~/my-nix nixpkgs#hello nixpkgs#bashInteractive --command bash
    

    Note that it's necessary to specify bash explicitly because your default shell (e.g. /bin/bash) generally will not exist in the chroot.

Description

nix shell runs a command in an environment in which the $PATH variable provides the specified installables. If no command is specified, it starts the default shell of your user account specified by $SHELL.

Use as a #!-interpreter

You can use nix 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
#! nix shell installables --command real-interpreter

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 installables are the attribute names of the dependencies in Nixpkgs.

The lines starting with #! nix specify 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
#! nix shell github:tomberek/-#python3With.prettytable --command python

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
#! nix shell github:tomberek/-#perlWith.HTMLTokeParserSimple.LWP --command perl -x

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
#! nix shell --impure --expr ``
#! nix with (import (builtins.getFlake ''nixpkgs'') {});
#! nix terraform.withPlugins (plugins: [ plugins.openstack ])
#! nix ``
#! nix --command bash

terraform "$@"

Note

You must use double backticks (``) 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 21.11 stable branch):

#!/usr/bin/env nix
#!nix shell --override-input nixpkgs github:NixOS/nixpkgs/nixos-21.11
#!nix github:tomberek/-#haskellWith.download-curl.tagsoup --command runghc

import Network.Curl.Download
import Text.HTML.TagSoup
import Data.Either
import Data.ByteString.Char8 (unpack)

-- Fetch nixos.org and print all hrefs.
main = do
  resp <- openURI "https://nixos.org/"
  let tags = filter (isTagOpenName "a") $ parseTags $ unpack $ fromRight undefined resp
  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 --override-input nixpkgs github:NixOS/nixpkgs/eabc38219184cc3e04a974fe31857d8e0eac098d

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
#! nix shell --impure --file deps.nix -i python

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

with import <nixpkgs> {};
python3.withPackages (ps: with ps; [ prettytable ])

Options

  • --command / -c command args

    Command and arguments to be executed, defaulting to $SHELL

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change environment variables

  • --ignore-env / -i

    Clear the entire environment, except for those specified with --keep-env-var.

  • --keep-env-var / -k name

    Keep the environment variable name, when using --ignore-env.

  • --set-env-var / -s name value

    Sets an environment variable name with value.

  • --unset-env-var / -u name

    Unset the environment variable name.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix eval - evaluate a Nix expression

Synopsis

nix eval [option...] installable

Examples

  • Evaluate a Nix expression given on the command line:

    # nix eval --expr '1 + 2'
    
  • Evaluate a Nix expression to JSON:

    # nix eval --json --expr '{ x = 1; }'
    {"x":1}
    
  • Evaluate a Nix expression from a file:

    # nix eval --file ./my-nixpkgs hello.name
    
  • Get the current version of the nixpkgs flake:

    # nix eval --raw nixpkgs#lib.version
    
  • Print the store path of the Hello package:

    # nix eval --raw nixpkgs#hello
    
  • Get a list of checks in the nix flake:

    # nix eval nix#checks.x86_64-linux --apply builtins.attrNames
    
  • Generate a directory with the specified contents:

    # nix eval --write-to ./out --expr '{ foo = "bar"; subdir.bla = "123"; }'
    # cat ./out/foo
    bar
    # cat ./out/subdir/bla
    123
    
    

Description

This command evaluates the given Nix expression, and prints the result on standard output.

It also evaluates any nested attribute values and list items.

Output format

nix eval can produce output in several formats:

  • By default, the evaluation result is printed as a Nix expression.

  • With --json, the evaluation result is printed in JSON format. Note that this fails if the result contains values that are not representable as JSON, such as functions.

  • With --raw, the evaluation result must be a string, which is printed verbatim, without any quoting.

  • With --write-to path, the evaluation result must be a string or a nested attribute set whose leaf values are strings. These strings are written to files named path/attrpath. path must not already exist.

Options

  • --apply expr

    Apply the function expr to each argument.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --raw

    Print strings without quotes or escaping.

  • --read-only

    Do not instantiate each evaluated derivation. This improves performance, but can cause errors when accessing store paths of derivations during evaluation.

  • --write-to path

    Write a string or attrset of strings to path.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake - manage Nix flakes

Synopsis

nix flake [option...] subcommand

where subcommand is one of the following:

Description

nix flake provides subcommands for creating, modifying and querying Nix flakes. Flakes are the unit for packaging Nix code in a reproducible and discoverable way. They can have dependencies on other flakes, making it possible to have multi-repository Nix projects.

A flake is a filesystem tree (typically fetched from a Git repository or a tarball) that contains a file named flake.nix in the root directory. flake.nix specifies some metadata about the flake such as dependencies (called inputs), as well as its outputs (the Nix values such as packages or NixOS modules provided by the flake).

Flake references

Flake references (flakerefs) are a way to specify the location of a flake. These have two different forms:

Attribute set representation

Example:

{
  type = "github";
  owner = "NixOS";
  repo = "nixpkgs";
}

The only required attribute is type. The supported types are listed below.

URL-like syntax

Example:

github:NixOS/nixpkgs

These are used on the command line as a more convenient alternative to the attribute set representation. For instance, in the command

# nix build github:NixOS/nixpkgs#hello

github:NixOS/nixpkgs is a flake reference (while hello is an output attribute). They are also allowed in the inputs attribute of a flake, e.g.

inputs.nixpkgs.url = "github:NixOS/nixpkgs";

is equivalent to

inputs.nixpkgs = {
  type = "github";
  owner = "NixOS";
  repo = "nixpkgs";
};

Following RFC 3986, characters outside of the allowed range (i.e. neither reserved characters nor unreserved characters) must be percent-encoded.

Examples

Here are some examples of flake references in their URL-like representation:

  • nixpkgs: The nixpkgs entry in the flake registry.
  • nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293: The nixpkgs entry in the flake registry, with its Git revision overridden to a specific value.
  • github:NixOS/nixpkgs: The master branch of the NixOS/nixpkgs repository on GitHub.
  • github:NixOS/nixpkgs/nixos-20.09: The nixos-20.09 branch of the nixpkgs repository.
  • github:NixOS/nixpkgs/pull/357207/head: The 357207 pull request of the nixpkgs repository.
  • github:NixOS/nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293: A specific revision of the nixpkgs repository.
  • github:edolstra/nix-warez?dir=blender: A flake in a subdirectory of a GitHub repository.
  • git+https://github.com/NixOS/patchelf: A Git repository.
  • git+https://github.com/NixOS/patchelf?ref=master: A specific branch of a Git repository.
  • git+https://github.com/NixOS/patchelf?ref=master&rev=f34751b88bd07d7f44f5cd3200fb4122bf916c7e: A specific branch and revision of a Git repository.
  • https://github.com/NixOS/patchelf/archive/master.tar.gz: A tarball flake.

Path-like syntax

Flakes corresponding to a local path can also be referred to by a direct path reference, either /absolute/path/to/the/flake or./relative/path/to/the/flake. Note that the leading ./ is mandatory for relative paths. If it is omitted, the path will be interpreted as URL-like syntax, which will cause error messages like this:

error: cannot find flake 'flake:relative/path/to/the/flake' in the flake registries

The semantic of such a path is as follows:

  • If the directory is part of a Git repository, then the input will be treated as a git+file: URL, otherwise it will be treated as a path: url;
  • If the directory doesn't contain a flake.nix file, then Nix will search for such a file upwards in the file system hierarchy until it finds any of:
    1. The Git repository root, or
    2. The filesystem root (/), or
    3. A folder on a different mount point.

Contrary to URL-like references, path-like flake references can contain arbitrary unicode characters (except # and ?).

Examples

  • .: The flake to which the current directory belongs.
  • /home/alice/src/patchelf: A flake in some other directory.
  • ./../sub directory/with Ûñî©ôδ€: A flake in another relative directory that has Unicode characters in its name.

Flake reference attributes

The following generic flake reference attributes are supported:

  • dir: The subdirectory of the flake in which flake.nix is located. This parameter enables having multiple flakes in a repository or tarball. The default is the root directory of the flake.

  • narHash: The hash of the Nix Archive (NAR) serialisation (in SRI format) of the contents of the flake. This is useful for flake types such as tarballs that lack a unique content identifier such as a Git commit hash.

In addition, the following attributes are common to several flake reference types:

  • rev: A Git or Mercurial commit hash.

  • ref: A Git or Mercurial branch or tag name.

Finally, some attributes are typically not specified by the user, but can occur in locked flake references and are available to Nix code:

  • revCount: The number of ancestors of the commit rev.

  • lastModified: The timestamp (in seconds since the Unix epoch) of the last modification of this version of the flake. For Git/Mercurial flakes, this is the commit time of commit rev, while for tarball flakes, it's the most recent timestamp of any file inside the tarball.

Types

Currently the type attribute can be one of the following:

  • indirect: The default. These are symbolic references to flakes that are looked up in the flake registries. These have the form

    [flake:]<flake-id>(/<rev-or-ref>(/rev)?)?
    

    These perform a lookup of <flake-id> in the flake registry. For example, nixpkgs and nixpkgs/release-20.09 are indirect flake references. The specified rev and/or ref are merged with the entry in the registry; see nix registry for details.

    For example, these are valid indirect flake references:

    • nixpkgs
    • nixpkgs/nixos-unstable
    • nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293
    • nixpkgs/nixos-unstable/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293
    • sub/dir (if a flake named sub is in the registry)
  • path: arbitrary local directories. The required attribute path specifies the path of the flake. The URL form is

    path:<path>(\?<params>)?
    

    where path is an absolute path to a directory in the file system containing a file named flake.nix.

    If the flake at path is not inside a git repository, the path: prefix is implied and can be omitted.

    If path is a relative path (i.e. if it does not start with /), it is interpreted as follows:

    • If path is a command line argument, it is interpreted relative to the current directory.

    • If path is used in a flake.nix, it is interpreted relative to the directory containing that flake.nix. However, the resolved path must be in the same tree. For instance, a flake.nix in the root of a tree can use path:./foo to access the flake in subdirectory foo, but path:../bar is illegal. On the other hand, a flake in the /foo directory of a tree can use path:../bar to refer to the flake in /bar.

    Path inputs can be specified with path values in flake.nix. Path values are a syntax for path inputs, and they are converted by

    1. resolving them into relative paths, relative to the base directory of flake.nix
    2. escaping URL characters (refer to IETF RFC?)
    3. prepending path:

    Note that the allowed syntax for path values in flake inputs may be more restrictive than general Nix, so you may need to use path: if your path contains certain special characters. See Path literals

    Note that if you omit path:, relative paths must start with . to avoid ambiguity with registry lookups (e.g. nixpkgs is a registry lookup; ./nixpkgs is a relative path).

    For example, these are valid path flake references:

    • path:/home/user/sub/dir
    • /home/user/sub/dir (if dir/flake.nix is not in a git repository)
    • path:sub/dir
    • ./sub/dir
    • path:../parent
  • git: Git repositories. The location of the repository is specified by the attribute url.

    They have the URL form

    git(+http|+https|+ssh|+git|+file):(//<server>)?<path>(\?<params>)?
    

    If path starts with / (or ./ when used as an argument on the command line) and is a local path to a git repository, the leading git: or +file prefixes are implied and can be omitted.

    The ref attribute defaults to resolving the HEAD reference.

    The rev attribute must denote a commit that exists in the branch or tag specified by the ref attribute, since Nix doesn't do a full clone of the remote repository by default (and the Git protocol doesn't allow fetching a rev without a known ref). The default is the commit currently pointed to by ref.

    When git+file is used without specifying ref or rev, files are fetched directly from the local path as long as they have been added to the Git repository. If there are uncommitted changes, the reference is treated as dirty and a warning is printed.

    For example, the following are valid Git flake references:

    • git:/home/user/sub/dir
    • /home/user/sub/dir (if dir/flake.nix is in a git repository)
    • ./sub/dir (when used on the command line and dir/flake.nix is in a git repository)
    • git+https://example.org/my/repo
    • git+https://example.org/my/repo?dir=flake1
    • git+https://example.org/my/repo?shallow=1 A shallow clone of the repository. For large repositories, the shallow clone option can significantly speed up fresh clones compared to non-shallow clones, while still providing faster updates than other fetch methods such as tarball: or github:.
    • git+ssh://git@github.com/NixOS/nix?ref=v1.2.3
    • git://github.com/edolstra/dwarffs?ref=unstable&rev=e486d8d40e626a20e06d792db8cc5ac5aba9a5b4
    • git+file:///home/my-user/some-repo/some-repo
  • mercurial: Mercurial repositories. The URL form is similar to the git type, except that the URL schema must be one of hg+http, hg+https, hg+ssh or hg+file.

  • tarball: Tarballs. The location of the tarball is specified by the attribute url.

    In URL form, the schema must be tarball+http://, tarball+https:// or tarball+file://. If the extension corresponds to a known archive format (.zip, .tar, .tgz, .tar.gz, .tar.xz, .tar.bz2 or .tar.zst), then the tarball+ can be dropped.

    This can also be used to set the location of gitea/forgejo branches. See here

  • file: Plain files or directory tarballs, either over http(s) or from the local disk.

    In URL form, the schema must be file+http://, file+https:// or file+file://. If the extension doesn’t correspond to a known archive format (as defined by the tarball fetcher), then the file+ prefix can be dropped.

  • github: A more efficient way to fetch repositories from GitHub. The following attributes are required:

    • owner: The owner of the repository.

    • repo: The name of the repository.

    These are downloaded as tarball archives, rather than through Git. This is often much faster and uses less disk space since it doesn't require fetching the entire history of the repository. On the other hand, it doesn't allow incremental fetching (but full downloads are often faster than incremental fetches!).

    The URL syntax for github flakes is:

    github:<owner>/<repo>(/<rev-or-ref>)?(\?<params>)?
    

    <rev-or-ref> specifies the name of a branch or tag (ref), or a commit hash (rev). Note that unlike Git, GitHub allows fetching by commit hash without specifying a branch or tag.

    You can also specify host as a parameter, to point to a custom GitHub Enterprise server.

    Some examples:

    • github:edolstra/dwarffs
    • github:edolstra/dwarffs/unstable
    • github:edolstra/dwarffs/d3f2baba8f425779026c6ec04021b2e927f61e31
    • github:internal/project?host=company-github.example.org
  • gitlab: Similar to github, is a more efficient way to fetch GitLab repositories. The following attributes are required:

    • owner: The owner of the repository.

    • repo: The name of the repository.

    Like github, these are downloaded as tarball archives.

    The URL syntax for gitlab flakes is:

    gitlab:<owner>/<repo>(/<rev-or-ref>)?(\?<params>)?

    <rev-or-ref> works the same as github. Either a branch or tag name (ref), or a commit hash (rev) can be specified.

    Since GitLab allows for self-hosting, you can specify host as a parameter, to point to any instances other than gitlab.com.

    Some examples:

    • gitlab:veloren/veloren
    • gitlab:veloren/veloren/master
    • gitlab:veloren/veloren/80a4d7f13492d916e47d6195be23acae8001985a
    • gitlab:openldap/openldap?host=git.openldap.org

    When accessing a project in a (nested) subgroup, make sure to URL-encode any slashes, i.e. replace / with %2F:

    • gitlab:veloren%2Fdev/rfcs
  • sourcehut: Similar to github, is a more efficient way to fetch SourceHut repositories. The following attributes are required:

    • owner: The owner of the repository (including leading ~).

    • repo: The name of the repository.

    Like github, these are downloaded as tarball archives.

    The URL syntax for sourcehut flakes is:

    sourcehut:<owner>/<repo>(/<rev-or-ref>)?(\?<params>)?

    <rev-or-ref> works the same as github. Either a branch or tag name (ref), or a commit hash (rev) can be specified.

    Since SourceHut allows for self-hosting, you can specify host as a parameter, to point to any instances other than git.sr.ht.

    Currently, ref name resolution only works for Git repositories. You can refer to Mercurial repositories by simply changing host to hg.sr.ht (or any other Mercurial instance). With the caveat that you must explicitly specify a commit hash (rev).

    Some examples:

    • sourcehut:~misterio/nix-colors
    • sourcehut:~misterio/nix-colors/main
    • sourcehut:~misterio/nix-colors?host=git.example.org
    • sourcehut:~misterio/nix-colors/182b4b8709b8ffe4e9774a4c5d6877bf6bb9a21c
    • sourcehut:~misterio/nix-colors/21c1a380a6915d890d408e9f22203436a35bb2de?host=hg.sr.ht

Flake format

As an example, here is a simple flake.nix that depends on the Nixpkgs flake and provides a single package (i.e. an installable derivation):

{
  description = "A flake for building Hello World";

  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-20.03";

  outputs = { self, nixpkgs }: {

    packages.x86_64-linux.default =
      # Notice the reference to nixpkgs here.
      with import nixpkgs { system = "x86_64-linux"; };
      stdenv.mkDerivation {
        name = "hello";
        src = self;
        buildPhase = "gcc -o hello ./hello.c";
        installPhase = "mkdir -p $out/bin; install -t $out/bin hello";
      };

  };
}

The following attributes are supported in flake.nix:

  • description: A short, one-line description of the flake.

  • inputs: An attrset specifying the dependencies of the flake (described below).

  • outputs: A function that, given an attribute set containing the outputs of each of the input flakes keyed by their identifier, yields the Nix values provided by this flake. Thus, in the example above, inputs.nixpkgs contains the result of the call to the outputs function of the nixpkgs flake.

    In addition to the outputs of each input, each input in inputs also contains some metadata about the inputs. These are:

    • outPath: The path in the Nix store of the flake's source tree. This way, the attribute set can be passed to import as if it was a path, as in the example above (import nixpkgs).

    • rev: The commit hash of the flake's repository, if applicable.

    • revCount: The number of ancestors of the revision rev. This is not available for github repositories, since they're fetched as tarballs rather than as Git repositories.

    • lastModifiedDate: The commit time of the revision rev, in the format %Y%m%d%H%M%S (e.g. 20181231100934). Unlike revCount, this is available for both Git and GitHub repositories, so it's useful for generating (hopefully) monotonically increasing version strings.

    • lastModified: The commit time of the revision rev as an integer denoting the number of seconds since 1970.

    • narHash: The SHA-256 (in SRI format) of the Nix Archive (NAR) serialisation NAR serialization of the flake's source tree.

    The value returned by the outputs function must be an attribute set. The attributes can have arbitrary values; however, various nix subcommands require specific attributes to have a specific value (e.g. packages.x86_64-linux must be an attribute set of derivations built for the x86_64-linux platform).

  • nixConfig: a set of nix.conf options to be set when evaluating any part of a flake. In the interests of security, only a small set of set of options is allowed to be set without confirmation so long as accept-flake-config is not enabled in the global configuration:

Flake inputs

The attribute inputs specifies the dependencies of a flake, as an attrset mapping input names to flake references. For example, the following specifies a dependency on the nixpkgs and import-cargo repositories:

# A GitHub repository.
inputs.import-cargo = {
  type = "github";
  owner = "edolstra";
  repo = "import-cargo";
};

# An indirection through the flake registry.
inputs.nixpkgs = {
  type = "indirect";
  id = "nixpkgs";
};

Alternatively, you can use the URL-like syntax:

inputs.import-cargo.url = "github:edolstra/import-cargo";
inputs.nixpkgs.url = "nixpkgs";

Each input is fetched, evaluated and passed to the outputs function as a set of attributes with the same name as the corresponding input. The special input named self refers to the outputs and source tree of this flake. Thus, a typical outputs function looks like this:

outputs = { self, nixpkgs, import-cargo }: {
  ... outputs ...
};

It is also possible to omit an input entirely and only list it as expected function argument to outputs. Thus,

outputs = { self, nixpkgs }: ...;

without an inputs.nixpkgs attribute is equivalent to

inputs.nixpkgs = {
  type = "indirect";
  id = "nixpkgs";
};

Repositories that don't contain a flake.nix can also be used as inputs, by setting the input's flake attribute to false:

inputs.grcov = {
  type = "github";
  owner = "mozilla";
  repo = "grcov";
  flake = false;
};

outputs = { self, nixpkgs, grcov }: {
  packages.x86_64-linux.grcov = stdenv.mkDerivation {
    src = grcov;
    ...
  };
};

Transitive inputs can be overridden from a flake.nix file. For example, the following overrides the nixpkgs input of the nixops input:

inputs.nixops.inputs.nixpkgs = {
  type = "github";
  owner = "my-org";
  repo = "nixpkgs";
};

It is also possible to "inherit" an input from another input. This is useful to minimize flake dependencies. For example, the following sets the nixpkgs input of the top-level flake to be equal to the nixpkgs input of the dwarffs input of the top-level flake:

inputs.nixpkgs.follows = "dwarffs/nixpkgs";

The value of the follows attribute is a /-separated sequence of input names denoting the path of inputs to be followed from the root flake.

Overrides and follows can be combined, e.g.

inputs.nixops.inputs.nixpkgs.follows = "dwarffs/nixpkgs";

sets the nixpkgs input of nixops to be the same as the nixpkgs input of dwarffs. It is worth noting, however, that it is generally not useful to eliminate transitive nixpkgs flake inputs in this way. Most flakes provide their functionality through Nixpkgs overlays or NixOS modules, which are composed into the top-level flake's nixpkgs input; so their own nixpkgs input is usually irrelevant.

Lock files

Inputs specified in flake.nix are typically "unlocked" in the sense that they don't specify an exact revision. To ensure reproducibility, Nix will automatically generate and use a lock file called flake.lock in the flake's directory. The lock file is a UTF-8 JSON file. It contains a graph structure isomorphic to the graph of dependencies of the root flake. Each node in the graph (except the root node) maps the (usually) unlocked input specifications in flake.nix to locked input specifications. Each node also contains some metadata, such as the dependencies (outgoing edges) of the node.

For example, if flake.nix has the inputs in the example above, then the resulting lock file might be:

{
  "version": 7,
  "root": "n1",
  "nodes": {
    "n1": {
      "inputs": {
        "nixpkgs": "n2",
        "import-cargo": "n3",
        "grcov": "n4"
      }
    },
    "n2": {
      "inputs": {},
      "locked": {
        "owner": "edolstra",
        "repo": "nixpkgs",
        "rev": "7f8d4b088e2df7fdb6b513bc2d6941f1d422a013",
        "type": "github",
        "lastModified": 1580555482,
        "narHash": "sha256-OnpEWzNxF/AU4KlqBXM2s5PWvfI5/BS6xQrPvkF5tO8="
      },
      "original": {
        "id": "nixpkgs",
        "type": "indirect"
      }
    },
    "n3": {
      "inputs": {},
      "locked": {
        "owner": "edolstra",
        "repo": "import-cargo",
        "rev": "8abf7b3a8cbe1c8a885391f826357a74d382a422",
        "type": "github",
        "lastModified": 1567183309,
        "narHash": "sha256-wIXWOpX9rRjK5NDsL6WzuuBJl2R0kUCnlpZUrASykSc="
      },
      "original": {
        "owner": "edolstra",
        "repo": "import-cargo",
        "type": "github"
      }
    },
    "n4": {
      "inputs": {},
      "locked": {
        "owner": "mozilla",
        "repo": "grcov",
        "rev": "989a84bb29e95e392589c4e73c29189fd69a1d4e",
        "type": "github",
        "lastModified": 1580729070,
        "narHash": "sha256-235uMxYlHxJ5y92EXZWAYEsEb6mm+b069GAd+BOIOxI="
      },
      "original": {
        "owner": "mozilla",
        "repo": "grcov",
        "type": "github"
      },
      "flake": false
    }
  }
}

This graph has 4 nodes: the root flake, and its 3 dependencies. The nodes have arbitrary labels (e.g. n1). The label of the root node of the graph is specified by the root attribute. Nodes contain the following fields:

  • inputs: The dependencies of this node, as a mapping from input names (e.g. nixpkgs) to node labels (e.g. n2).

  • original: The original input specification from flake.nix, as a set of builtins.fetchTree arguments.

  • locked: The locked input specification, as a set of builtins.fetchTree arguments. Thus, in the example above, when we build this flake, the input nixpkgs is mapped to revision 7f8d4b088e2df7fdb6b513bc2d6941f1d422a013 of the edolstra/nixpkgs repository on GitHub.

    It also includes the attribute narHash, specifying the expected contents of the tree in the Nix store (as computed by nix hash-path), and may include input-type-specific attributes such as the lastModified or revCount. The main reason for these attributes is to allow flake inputs to be substituted from a binary cache: narHash allows the store path to be computed, while the other attributes are necessary because they provide information not stored in the store path.

    The attributes in locked are considered "final", meaning that they are the only ones that are passed via the arguments of the outputs function of a flake. For instance, if locked contains a lastModified attribute while the fetcher does not return a lastModified attribute, then the lastModified attribute will be passed to the outputs function. Conversely, if locked does not contain a lastModified attribute while the fetcher does return a lastModified attribute, then no lastModified attribute will be passed. If locked contains a lastModifed attribute and the fetcher returns a lastModified attribute, then they must have the same value.

  • flake: A Boolean denoting whether this is a flake or non-flake dependency. Corresponds to the flake attribute in the inputs attribute in flake.nix.

The original and locked attributes are omitted for the root node. This is because we cannot record the commit hash or content hash of the root flake, since modifying flake.lock will invalidate these.

The graph representation of lock files allows circular dependencies between flakes. For example, here are two flakes that reference each other:

{
  inputs.b = ... location of flake B ...;
  # Tell the 'b' flake not to fetch 'a' again, to ensure its 'a' is
  # *this* 'a'.
  inputs.b.inputs.a.follows = "";
  outputs = { self, b }: {
    foo = 123 + b.bar;
    xyzzy = 1000;
  };
}

and

{
  inputs.a = ... location of flake A ...;
  inputs.a.inputs.b.follows = "";
  outputs = { self, a }: {
    bar = 456 + a.xyzzy;
  };
}

Lock files transitively lock direct as well as indirect dependencies. That is, if a lock file exists and is up to date, Nix will not look at the lock files of dependencies. However, lock file generation itself does use the lock files of dependencies by default.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake archive - copy a flake and all its inputs to a store

Synopsis

nix flake archive [option...] flake-url

Examples

  • Copy the dwarffs flake and its dependencies to a binary cache:

    # nix flake archive --to file:///tmp/my-cache dwarffs
    
  • Fetch the dwarffs flake and its dependencies to the local Nix store:

    # nix flake archive dwarffs
    
  • Print the store paths of the flake sources of NixOps without fetching them:

    # nix flake archive --json --dry-run nixops
    
  • Upload all flake inputs to a different machine for remote evaluation

    # nix flake archive --to ssh://some-machine
    

    On the remote machine the flake can then be accessed via its store path. That's computed like this:

    # nix flake metadata --json | jq -r '.path'
    

Description

Copy a flake and all its inputs to a store. This is useful i.e. to evaluate flakes on a different host.

Options

  • --dry-run

    Show what this command would do without doing it.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --to store-uri

    URI of the destination Nix store

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake check - check whether the flake evaluates and run its tests

Synopsis

nix flake check [option...] flake-url

Examples

  • Evaluate the flake in the current directory, and build its checks:

    # nix flake check
    
  • Verify that the patchelf flake evaluates, but don't build its checks:

    # nix flake check --no-build github:NixOS/patchelf
    

Description

This command verifies that the flake specified by flake reference flake-url can be evaluated successfully (as detailed below), and that the derivations specified by the flake's checks output can be built successfully.

If the keep-going option is set to true, Nix will keep evaluating as much as it can and report the errors as it encounters them. Otherwise it will stop at the first error.

Evaluation checks

The following flake output attributes must be derivations:

  • checks.system.name
  • defaultPackage.system
  • devShell.system
  • devShells.system.name
  • nixosConfigurations.name.config.system.build.toplevel
  • packages.system.name

The following flake output attributes must be app definitions:

  • apps.system.name
  • defaultApp.system

The following flake output attributes must be template definitions:

  • defaultTemplate
  • templates.name

The following flake output attributes must be Nixpkgs overlays:

  • overlay
  • overlays.name

The following flake output attributes must be NixOS modules:

  • nixosModule
  • nixosModules.name

The following flake output attributes must be bundlers:

  • bundlers.name
  • defaultBundler

In addition, the hydraJobs output is evaluated in the same way as Hydra's hydra-eval-jobs (i.e. as a arbitrarily deeply nested attribute set of derivations). Similarly, the legacyPackages.system output is evaluated like nix-env --query --available .

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake clone - clone flake repository

Synopsis

nix flake clone [option...] flake-url

Examples

  • Check out the source code of the dwarffs flake and build it:

    # nix flake clone dwarffs --dest dwarffs
    # cd dwarffs
    # nix build
    

Description

This command performs a Git or Mercurial clone of the repository containing the source code of the flake flake-url.

Options

  • --dest / -f path

    Clone the flake to path dest.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake info - show flake metadata

Synopsis

nix flake info [option...] flake-url

Examples

  • Show what dwarffs resolves to:

    # nix flake metadata dwarffs
    Resolved URL:  github:edolstra/dwarffs
    Locked URL:    github:edolstra/dwarffs/f691e2c991e75edb22836f1dbe632c40324215c5
    Description:   A filesystem that fetches DWARF debug info from the Internet on demand
    Path:          /nix/store/769s05vjydmc2lcf6b02az28wsa9ixh1-source
    Revision:      f691e2c991e75edb22836f1dbe632c40324215c5
    Last modified: 2021-01-21 15:41:26
    Inputs:
    ├───nix: github:NixOS/nix/6254b1f5d298ff73127d7b0f0da48f142bdc753c
    │   ├───lowdown-src: github:kristapsdz/lowdown/1705b4a26fbf065d9574dce47a94e8c7c79e052f
    │   └───nixpkgs: github:NixOS/nixpkgs/ad0d20345219790533ebe06571f82ed6b034db31
    └───nixpkgs follows input 'nix/nixpkgs'
    
  • Show information about dwarffs in JSON format:

    # nix flake metadata dwarffs --json | jq .
    {
      "description": "A filesystem that fetches DWARF debug info from the Internet on demand",
      "lastModified": 1597153508,
      "locked": {
        "lastModified": 1597153508,
        "narHash": "sha256-VHg3MYVgQ12LeRSU2PSoDeKlSPD8PYYEFxxwkVVDRd0=",
        "owner": "edolstra",
        "repo": "dwarffs",
        "rev": "d181d714fd36eb06f4992a1997cd5601e26db8f5",
        "type": "github"
      },
      "locks": { ... },
      "original": {
        "id": "dwarffs",
        "type": "indirect"
      },
      "originalUrl": "flake:dwarffs",
      "path": "/nix/store/hang3792qwdmm2n0d9nsrs5n6bsws6kv-source",
      "resolved": {
        "owner": "edolstra",
        "repo": "dwarffs",
        "type": "github"
      },
      "resolvedUrl": "github:edolstra/dwarffs",
      "revision": "d181d714fd36eb06f4992a1997cd5601e26db8f5",
      "url": "github:edolstra/dwarffs/d181d714fd36eb06f4992a1997cd5601e26db8f5"
    }
    

Description

This command shows information about the flake specified by the flake reference flake-url. It resolves the flake reference using the flake registry, fetches it, and prints some meta data. This includes:

  • Resolved URL: If flake-url is a flake identifier, then this is the flake reference that specifies its actual location, looked up in the flake registry.

  • Locked URL: A flake reference that contains a commit or content hash and thus uniquely identifies a specific flake version.

  • Description: A one-line description of the flake, taken from the description field in flake.nix.

  • Path: The store path containing the source code of the flake.

  • Revision: The Git or Mercurial commit hash of the locked flake.

  • Revisions: The number of ancestors of the Git or Mercurial commit of the locked flake. Note that this is not available for github flakes.

  • Last modified: For Git or Mercurial flakes, this is the commit time of the commit of the locked flake; for tarball flakes, it's the most recent timestamp of any file inside the tarball.

  • Inputs: The flake inputs with their corresponding lock file entries.

With --json, the output is a JSON object with the following fields:

  • original and originalUrl: The flake reference specified by the user (flake-url) in attribute set and URL representation.

  • resolved and resolvedUrl: The resolved flake reference (see above) in attribute set and URL representation.

  • locked and lockedUrl: The locked flake reference (see above) in attribute set and URL representation.

  • description: See Description above.

  • path: See Path above.

  • revision: See Revision above.

  • revCount: See Revisions above.

  • lastModified: See Last modified above.

  • locks: The contents of flake.lock.

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake init - create a flake in the current directory from a template

Synopsis

nix flake init [option...]

Examples

  • Create a flake using the default template:

    # nix flake init
    
  • List available templates:

    # nix flake show templates
    
  • Create a flake from a specific template:

    # nix flake init -t templates#simpleContainer
    

Description

This command creates a flake in the current directory by copying the files of a template. It will not overwrite existing files. The default template is templates#templates.default, but this can be overridden using -t.

Template definitions

A flake can declare templates through its templates output attribute. A template has the following attributes:

  • description: A one-line description of the template, in CommonMark syntax.

  • path: The path of the directory to be copied.

  • welcomeText: A block of markdown text to display when a user initializes a new flake based on this template.

Here is an example:

outputs = { self }: {

  templates.rust = {
    path = ./rust;
    description = "A simple Rust/Cargo project";
    welcomeText = ''
      # Simple Rust/Cargo Template
      ## Intended usage
      The intended usage of this flake is...

      ## More info
      - [Rust language](https://www.rust-lang.org/)
      - [Rust on the NixOS Wiki](https://wiki.nixos.org/wiki/Rust)
      - ...
    '';
  };

  templates.default = self.templates.rust;
}

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake lock - create missing lock file entries

Synopsis

nix flake lock [option...] flake-url

Examples

  • Create the lock file for the flake in the current directory:

    # nix flake lock
    warning: creating lock file '/home/myself/repos/testflake/flake.lock':
    • Added input 'nix':
        'github:NixOS/nix/9fab14adbc3810d5cc1f88672fde1eee4358405c' (2023-06-28)
    • Added input 'nixpkgs':
        'github:NixOS/nixpkgs/3d2d8f281a27d466fa54b469b5993f7dde198375' (2023-06-30)
    
  • Add missing inputs to the lock file for a flake in a different directory:

    # nix flake lock ~/repos/another
    warning: updating lock file '/home/myself/repos/another/flake.lock':
    • Added input 'nixpkgs':
        'github:NixOS/nixpkgs/3d2d8f281a27d466fa54b469b5993f7dde198375' (2023-06-30)
    

    Note

    When trying to refer to a flake in a subdirectory, write ./another instead of another. Otherwise Nix will try to look up the flake in the registry.

Description

This command updates the lock file of a flake (flake.lock) so that it contains an up-to-date lock for every flake input specified in flake.nix. Lock file entries are aready up-to-date are not modified.

If you want to update existing lock entries, use nix flake update

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake metadata - show flake metadata

Synopsis

nix flake metadata [option...] flake-url

Examples

  • Show what dwarffs resolves to:

    # nix flake metadata dwarffs
    Resolved URL:  github:edolstra/dwarffs
    Locked URL:    github:edolstra/dwarffs/f691e2c991e75edb22836f1dbe632c40324215c5
    Description:   A filesystem that fetches DWARF debug info from the Internet on demand
    Path:          /nix/store/769s05vjydmc2lcf6b02az28wsa9ixh1-source
    Revision:      f691e2c991e75edb22836f1dbe632c40324215c5
    Last modified: 2021-01-21 15:41:26
    Inputs:
    ├───nix: github:NixOS/nix/6254b1f5d298ff73127d7b0f0da48f142bdc753c
    │   ├───lowdown-src: github:kristapsdz/lowdown/1705b4a26fbf065d9574dce47a94e8c7c79e052f
    │   └───nixpkgs: github:NixOS/nixpkgs/ad0d20345219790533ebe06571f82ed6b034db31
    └───nixpkgs follows input 'nix/nixpkgs'
    
  • Show information about dwarffs in JSON format:

    # nix flake metadata dwarffs --json | jq .
    {
      "description": "A filesystem that fetches DWARF debug info from the Internet on demand",
      "lastModified": 1597153508,
      "locked": {
        "lastModified": 1597153508,
        "narHash": "sha256-VHg3MYVgQ12LeRSU2PSoDeKlSPD8PYYEFxxwkVVDRd0=",
        "owner": "edolstra",
        "repo": "dwarffs",
        "rev": "d181d714fd36eb06f4992a1997cd5601e26db8f5",
        "type": "github"
      },
      "locks": { ... },
      "original": {
        "id": "dwarffs",
        "type": "indirect"
      },
      "originalUrl": "flake:dwarffs",
      "path": "/nix/store/hang3792qwdmm2n0d9nsrs5n6bsws6kv-source",
      "resolved": {
        "owner": "edolstra",
        "repo": "dwarffs",
        "type": "github"
      },
      "resolvedUrl": "github:edolstra/dwarffs",
      "revision": "d181d714fd36eb06f4992a1997cd5601e26db8f5",
      "url": "github:edolstra/dwarffs/d181d714fd36eb06f4992a1997cd5601e26db8f5"
    }
    

Description

This command shows information about the flake specified by the flake reference flake-url. It resolves the flake reference using the flake registry, fetches it, and prints some meta data. This includes:

  • Resolved URL: If flake-url is a flake identifier, then this is the flake reference that specifies its actual location, looked up in the flake registry.

  • Locked URL: A flake reference that contains a commit or content hash and thus uniquely identifies a specific flake version.

  • Description: A one-line description of the flake, taken from the description field in flake.nix.

  • Path: The store path containing the source code of the flake.

  • Revision: The Git or Mercurial commit hash of the locked flake.

  • Revisions: The number of ancestors of the Git or Mercurial commit of the locked flake. Note that this is not available for github flakes.

  • Last modified: For Git or Mercurial flakes, this is the commit time of the commit of the locked flake; for tarball flakes, it's the most recent timestamp of any file inside the tarball.

  • Inputs: The flake inputs with their corresponding lock file entries.

With --json, the output is a JSON object with the following fields:

  • original and originalUrl: The flake reference specified by the user (flake-url) in attribute set and URL representation.

  • resolved and resolvedUrl: The resolved flake reference (see above) in attribute set and URL representation.

  • locked and lockedUrl: The locked flake reference (see above) in attribute set and URL representation.

  • description: See Description above.

  • path: See Path above.

  • revision: See Revision above.

  • revCount: See Revisions above.

  • lastModified: See Last modified above.

  • locks: The contents of flake.lock.

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake new - create a flake in the specified directory from a template

Synopsis

nix flake new [option...] dest-dir

Examples

  • Create a flake using the default template in the directory hello:

    # nix flake new hello
    
  • List available templates:

    # nix flake show templates
    
  • Create a flake from a specific template in the directory hello:

    # nix flake new hello -t templates#trivial
    

Description

This command creates a flake in the directory dest-dir, which must not already exist. It's equivalent to:

# mkdir dest-dir
# cd dest-dir
# nix flake init

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake prefetch - download the source tree denoted by a flake reference into the Nix store

Synopsis

nix flake prefetch [option...] flake-url

Examples

  • Download a tarball and unpack it:

    # nix flake prefetch https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.5.tar.xz --out-link ./result
    Downloaded 'https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.5.tar.xz?narHash=sha256-3XYHZANT6AFBV0BqegkAZHbba6oeDkIUCDwbATLMhAY='
    to '/nix/store/sl5vvk8mb4ma1sjyy03kwpvkz50hd22d-source' (hash
    'sha256-3XYHZANT6AFBV0BqegkAZHbba6oeDkIUCDwbATLMhAY=').
    
    # cat ./result/README
    Linux kernel
    …
    
  • Download the dwarffs flake (looked up in the flake registry):

    # nix flake prefetch dwarffs --json
    {"hash":"sha256-VHg3MYVgQ12LeRSU2PSoDeKlSPD8PYYEFxxwkVVDRd0="
    ,"storePath":"/nix/store/hang3792qwdmm2n0d9nsrs5n6bsws6kv-source"}
    

Description

This command downloads the source tree denoted by flake reference flake-url. Note that this does not need to be a flake (i.e. it does not have to contain a flake.nix file).

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --out-link / -o path

    Create symlink named path to the resulting store path.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake show - show the outputs provided by a flake

Synopsis

nix flake show [option...] flake-url

Examples

  • Show the output attributes provided by the patchelf flake:

    github:NixOS/patchelf/f34751b88bd07d7f44f5cd3200fb4122bf916c7e
    ├───checks
    │   ├───aarch64-linux
    │   │   └───build: derivation 'patchelf-0.12.20201207.f34751b'
    │   ├───i686-linux
    │   │   └───build: derivation 'patchelf-0.12.20201207.f34751b'
    │   └───x86_64-linux
    │       └───build: derivation 'patchelf-0.12.20201207.f34751b'
    ├───packages
    │   ├───aarch64-linux
    │   │   └───default: package 'patchelf-0.12.20201207.f34751b'
    │   ├───i686-linux
    │   │   └───default: package 'patchelf-0.12.20201207.f34751b'
    │   └───x86_64-linux
    │       └───default: package 'patchelf-0.12.20201207.f34751b'
    ├───hydraJobs
    │   ├───build
    │   │   ├───aarch64-linux: derivation 'patchelf-0.12.20201207.f34751b'
    │   │   ├───i686-linux: derivation 'patchelf-0.12.20201207.f34751b'
    │   │   └───x86_64-linux: derivation 'patchelf-0.12.20201207.f34751b'
    │   ├───coverage: derivation 'patchelf-coverage-0.12.20201207.f34751b'
    │   ├───release: derivation 'patchelf-0.12.20201207.f34751b'
    │   └───tarball: derivation 'patchelf-tarball-0.12.20201207.f34751b'
    └───overlay: Nixpkgs overlay
    

Description

This command shows the output attributes provided by the flake specified by flake reference flake-url. These are the top-level attributes in the outputs of the flake, as well as lower-level attributes for some standard outputs (e.g. packages or checks).

With --json, the output is in a JSON representation suitable for automatic processing by other tools.

Options

  • --all-systems

    Show the contents of outputs for all systems.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --legacy

    Show the contents of the legacyPackages output.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix flake update - update flake lock file

Synopsis

nix flake update [option...] inputs...

Examples

  • Update all inputs (i.e. recreate the lock file from scratch):

    # nix flake update
    warning: updating lock file '/home/myself/repos/testflake/flake.lock':
    • Updated input 'nix':
        'github:NixOS/nix/9fab14adbc3810d5cc1f88672fde1eee4358405c' (2023-06-28)
      → 'github:NixOS/nix/8927cba62f5afb33b01016d5c4f7f8b7d0adde3c' (2023-07-11)
    • Updated input 'nixpkgs':
        'github:NixOS/nixpkgs/3d2d8f281a27d466fa54b469b5993f7dde198375' (2023-06-30)
      → 'github:NixOS/nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293' (2023-07-05)
    
  • Update only a single input:

    # nix flake update nixpkgs
    warning: updating lock file '/home/myself/repos/testflake/flake.lock':
    • Updated input 'nixpkgs':
        'github:NixOS/nixpkgs/3d2d8f281a27d466fa54b469b5993f7dde198375' (2023-06-30)
      → 'github:NixOS/nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293' (2023-07-05)
    
  • Update multiple inputs:

    # nix flake update nixpkgs nixpkgs-unstable
    warning: updating lock file '/home/myself/repos/testflake/flake.lock':
    • Updated input 'nixpkgs':
        'github:nixos/nixpkgs/8f7492cce28977fbf8bd12c72af08b1f6c7c3e49' (2024-09-14)
      → 'github:nixos/nixpkgs/086b448a5d54fd117f4dc2dee55c9f0ff461bdc1' (2024-09-16)
    • Updated input 'nixpkgs-unstable':
        'github:nixos/nixpkgs/345c263f2f53a3710abe117f28a5cb86d0ba4059' (2024-09-13)
      → 'github:nixos/nixpkgs/99dc8785f6a0adac95f5e2ab05cc2e1bf666d172' (2024-09-16)
    
  • Update only a single input of a flake in a different directory:

    # nix flake update nixpkgs --flake ~/repos/another
    warning: updating lock file '/home/myself/repos/another/flake.lock':
    • Updated input 'nixpkgs':
        'github:NixOS/nixpkgs/3d2d8f281a27d466fa54b469b5993f7dde198375' (2023-06-30)
      → 'github:NixOS/nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293' (2023-07-05)
    

    Note

    When trying to refer to a flake in a subdirectory, write ./another instead of another. Otherwise Nix will try to look up the flake in the registry.

Description

This command updates the inputs in a lock file (flake.lock). By default, all inputs are updated. If the lock file doesn't exist yet, it will be created. If inputs are not in the lock file yet, they will be added.

Unlike other nix flake commands, nix flake update takes a list of names of inputs to update as its positional arguments and operates on the flake in the current directory. You can pass a different flake-url with --flake to override that default.

The related command nix flake lock also creates lock files and adds missing inputs, but is safer as it will never update inputs already in the lock file.

Options

  • --flake flake-url

    The flake to operate on. Default is the current directory.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix fmt - reformat your code in the standard style

Synopsis

nix fmt [option...] args...

Description

nix fmt calls the formatter specified in the flake.

Flags can be forwarded to the formatter by using -- followed by the flags.

Any arguments will be forwarded to the formatter. Typically these are the files to format.

Examples

With nixpkgs-fmt:

# flake.nix
{
  outputs = { nixpkgs, self }: {
    formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.nixpkgs-fmt;
  };
}

With nixfmt:

# flake.nix
{
  outputs = { nixpkgs, self }: {
    formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.nixfmt-rfc-style;
  };
}

With Alejandra:

# flake.nix
{
  outputs = { nixpkgs, self }: {
    formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.alejandra;
  };
}

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash - compute and convert cryptographic hashes

Synopsis

nix hash [option...] subcommand

where subcommand is one of the following:

Available commands:

  • nix hash file - print cryptographic hash of a regular file
  • nix hash path - print cryptographic hash of the NAR serialisation of a path
  • nix hash to-base16 - convert a hash to base-16 representation (deprecated, use nix hash convert instead)
  • nix hash to-base32 - convert a hash to base-32 representation (deprecated, use nix hash convert instead)
  • nix hash to-base64 - convert a hash to base-64 representation (deprecated, use nix hash convert instead)
  • nix hash to-sri - convert a hash to SRI representation (deprecated, use nix hash convert instead)

:

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash convert - convert between hash formats

Synopsis

nix hash convert [option...] hashes...

Examples

  • Convert a hash to nix32 (a base-32 encoding with a Nix-specific character set).

    $ nix hash convert --hash-algo sha1 --to nix32 800d59cfcd3c05e900cb4e214be48f6b886a08df
    vw46m23bizj4n8afrc0fj19wrp7mj3c0
    
  • Convert a hash to the sri format that includes an algorithm specification:

    # nix hash convert --hash-algo sha1 800d59cfcd3c05e900cb4e214be48f6b886a08df
    sha1-gA1Zz808BekAy04hS+SPa4hqCN8=
    

    or with an explicit --to format:

    # nix hash convert --hash-algo sha1 --to sri 800d59cfcd3c05e900cb4e214be48f6b886a08df
    sha1-gA1Zz808BekAy04hS+SPa4hqCN8=
    
  • Assert the input format of the hash:

    # nix hash convert --hash-algo sha256 --from nix32 ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=
    error: input hash 'ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=' does not have the expected format '--from nix32'
    
    # nix hash convert --hash-algo sha256 --from nix32 1b8m03r63zqhnjf7l5wnldhh7c134ap5vpj0850ymkq1iyzicy5s
    sha256-ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=
    

Description

nix hash convert converts hashes from one encoding to another.

Options

  • --from hash-format

    Hash format (base16, nix32, base64, sri).

  • --hash-algo hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512). Can be omitted for SRI hashes.

  • --to hash-format

    Hash format (base16, nix32, base64, sri). Default: sri.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash file - print cryptographic hash of a regular file

Synopsis

nix hash file [option...] paths...

Options

  • --base16

    Print the hash in base-16 format.

  • --base32

    Print the hash in base-32 (Nix-specific) format.

  • --base64

    Print the hash in base-64 format.

  • --sri

    Print the hash in SRI format.

  • --type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash path - print cryptographic hash of the NAR serialisation of a path

Synopsis

nix hash path [option...] paths...

Options

  • --algo hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --base16

    Print the hash in base-16 format.

  • --base32

    Print the hash in base-32 (Nix-specific) format.

  • --base64

    Print the hash in base-64 format.

  • --format hash-format

    Hash format (base16, nix32, base64, sri). Default: sri.

  • --mode file-ingestion-method

    How to compute the hash of the input. One of:

    • nar (the default): Serialises the input as a Nix Archive and passes that to the hash function.

    • flat: Assumes that the input is a single file and directly passes it to the hash function.

  • --sri

    Print the hash in SRI format.

  • --type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash to-base16 - convert a hash to base-16 representation (deprecated, use nix hash convert instead)

Synopsis

nix hash to-base16 [option...] strings...

Options

  • --type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512). Can be omitted for SRI hashes.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash to-base32 - convert a hash to base-32 representation (deprecated, use nix hash convert instead)

Synopsis

nix hash to-base32 [option...] strings...

Options

  • --type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512). Can be omitted for SRI hashes.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash to-base64 - convert a hash to base-64 representation (deprecated, use nix hash convert instead)

Synopsis

nix hash to-base64 [option...] strings...

Options

  • --type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512). Can be omitted for SRI hashes.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix hash to-sri - convert a hash to SRI representation (deprecated, use nix hash convert instead)

Synopsis

nix hash to-sri [option...] strings...

Options

  • --type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512). Can be omitted for SRI hashes.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix help - show help about nix or a particular subcommand

Synopsis

nix help [option...] subcommand...

Examples

  • Show help about nix in general:

    # nix help
    
  • Show help about a particular subcommand:

        # nix help flake info
    

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix help-stores - show help about store types and their settings

Synopsis

nix help-stores [option...]

Nix supports different types of stores:

Store URL format

Stores are specified using a URL-like syntax. For example, the command

# nix path-info --store https://cache.nixos.org/ --json \
  /nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1

fetches information about a store path in the HTTP binary cache located at https://cache.nixos.org/, which is a type of store.

Store URLs can specify store settings using URL query strings, i.e. by appending ?name1=value1&name2=value2&... to the URL. For instance,

--store ssh://machine.example.org?ssh-key=/path/to/my/key

tells Nix to access the store on a remote machine via the SSH protocol, using /path/to/my/key as the SSH private key. The supported settings for each store type are documented below.

The special store URL auto causes Nix to automatically select a store as follows:

Dummy Store

Store URL format: dummy://

This store type represents a store that contains no store paths and cannot be written to. It's useful when you want to use the Nix evaluator when no actual Nix store exists, e.g.

# nix eval --store dummy:// --expr '1 + 2'

Settings

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Experimental Local Overlay Store

Warning

This store is part of an experimental feature.

To use this store, make sure the local-overlay-store experimental feature is enabled. For example, include the following in nix.conf:

extra-experimental-features = local-overlay-store

Store URL format: local-overlay

This store type is a variation of the [local store] designed to leverage Linux's Overlay Filesystem (OverlayFS for short). Just as OverlayFS combines a lower and upper filesystem by treating the upper one as a patch against the lower, the local overlay store combines a lower store with an upper almost-[local store]. ("almost" because while the upper filesystems for OverlayFS is valid on its own, the upper almost-store is not a valid local store on its own because some references will dangle.) To use this store, you will first need to configure an OverlayFS mountpoint appropriately as Nix will not do this for you (though it will verify the mountpoint is configured correctly).

Conceptual parts of a local overlay store

This is a more abstract/conceptual description of the parts of a layered store, an authoritative reference. For more "practical" instructions, see the worked-out example in the next subsection.

The parts of a local overlay store are as follows:

  • Lower store:

    Specified with the lower-store setting.

    This is any store implementation that includes a store directory as part of the native operating system filesystem. For example, this could be a [local store], [local daemon store], or even another local overlay store.

    The local overlay store never tries to modify the lower store in any way. Something else could modify the lower store, but there are restrictions on this Nix itself requires that this store only grow, and not change in other ways. For example, new store objects can be added, but deleting or modifying store objects is not allowed in general, because that will confuse and corrupt any local overlay store using those objects. (In addition, the underlying filesystem overlay mechanism may impose additional restrictions, see below.)

    The lower store must not change while it is mounted as part of an overlay store. To ensure it does not, you might want to mount the store directory read-only (which then requires the [read-only] parameter to be set to true).

    • Lower store directory:

      Specified with lower-store.real setting.

      This is the directory used/exposed by the lower store.

      As specified above, Nix requires the local store can only grow not change in other ways. Linux's OverlayFS in addition imposes the further requirement that this directory cannot change at all. That means that, while any local overlay store exists that is using this store as a lower store, this directory must not change.

    • Lower metadata source:

      Not directly specified. A consequence of the lower-store setting, depending on the type of lower store chosen.

      This is abstract, just some way to read the metadata of lower store store objects. For example it could be a SQLite database (for the [local store]), or a socket connection (for the [local daemon store]).

      This need not be writable. As stated above a local overlay store never tries to modify its lower store. The lower store's metadata is considered part of the lower store, just as the store's file system objects that appear in the store directory are.

  • Upper almost-store:

    Not directly specified. Instead the constituent parts are independently specified as described below.

    This is almost but not quite just a [local store]. That is because taken in isolation, not as part of a local overlay store, by itself, it would appear corrupted. But combined with everything else as part of an overlay local store, it is valid.

    • Upper layer directory:

      Specified with upper-layer setting.

      This contains additional store objects (or, strictly speaking, their file system objects that the local overlay store will extend the lower store with).

    • Upper store directory:

      Specified with the real setting. This the same as the base local store setting, and can also be indirectly specified with the root setting.

      This contains all the store objects from each of the two directories.

      The lower store directory and upper layer directory are combined via OverlayFS to create this directory. Nix doesn't do this itself, because it typically wouldn't have the permissions to do so, so it is the responsibility of the user to set this up first. Nix can, however, optionally check that the OverlayFS mount settings appear as expected, matching Nix's own settings.

    • Upper SQLite database:

      Not directly specified. The location of the database instead depends on the state setting. It is always ${state}/db.

      This contains the metadata of all of the upper layer store objects (everything beyond their file system objects), and also duplicate copies of some lower layer store object's metadta. The duplication is so the metadata for the closure of upper layer store objects can be found entirely within the upper layer. (This allows us to use the same SQL Schema as the [local store]'s SQLite database, as foreign keys in that schema enforce closure metadata to be self-contained in this way.)

Example filesystem layout

Here is a worked out example of usage, following the concepts in the previous section.

Say we have the following paths:

  • /mnt/example/merged-store/nix/store

  • /mnt/example/store-a/nix/store

  • /mnt/example/store-b

Then the following store URI can be used to access a local-overlay store at /mnt/example/merged-store:

local-overlay://?root=/mnt/example/merged-store&lower-store=/mnt/example/store-a&upper-layer=/mnt/example/store-b

The lower store directory is located at /mnt/example/store-a/nix/store, while the upper layer is at /mnt/example/store-b.

Before accessing the overlay store you will need to ensure the OverlayFS mount is set up correctly:

mount -t overlay overlay \
  -o lowerdir="/mnt/example/store-a/nix/store" \
  -o upperdir="/mnt/example/store-b" \
  -o workdir="/mnt/example/workdir" \
  "/mnt/example/merged-store/nix/store"

Note that OverlayFS requires /mnt/example/workdir to be on the same volume as the upperdir.

By default, Nix will check that the mountpoint as been set up correctly and fail with an error if it has not. You can override this behaviour by passing check-mount=false if you need to.

Settings

  • check-mount

    Check that the overlay filesystem is correctly mounted.

    Nix does not manage the overlayfs mount point itself, but the correct functioning of the overlay store does depend on this mount point being set up correctly. Rather than just assume this is the case, check that the lowerdir and upperdir options are what we expect them to be. This check is on by default, but can be disabled if needed.

    Default: true

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • lower-store

    Store URL for the lower store. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Must be a store with a store dir on the file system. Must be used as OverlayFS lower layer for this store's store dir.

    Default: empty

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • read-only

    Allow this store to be opened when its database is on a read-only filesystem.

    Normally Nix will attempt to open the store database in read-write mode, even for querying (when write access is not needed), causing it to fail if the database is on a read-only filesystem.

    Enable read-only mode to disable locking and open the SQLite database with the immutable parameter set.

    Warning Do not use this unless the filesystem is read-only.

    Using it when the filesystem is writable can cause incorrect query results or corruption errors if the database is changed by another process. While the filesystem the database resides on might appear to be read-only, consider whether another user or system might have write access to it.

    Default: false

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • remount-hook

    Script or other executable to run when overlay filesystem needs remounting.

    This is occasionally necessary when deleting a store path that exists in both upper and lower layers. In such a situation, bypassing OverlayFS and deleting the path in the upper layer directly is the only way to perform the deletion without creating a "whiteout". However this causes the OverlayFS kernel data structures to get out-of-sync, and can lead to 'stale file handle' errors; remounting solves the problem.

    The store directory is passed as an argument to the invoked executable.

    Default: empty

  • require-sigs

    Whether store paths copied into this store should have a trusted signature.

    Default: true

  • root

    Directory prefixed to all other paths.

    Default: ``

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • upper-layer

    Directory containing the OverlayFS upper layer for this store's store dir.

    Default: empty

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Experimental SSH Store with filesystem mounted

Warning

This store is part of an experimental feature.

To use this store, make sure the mounted-ssh-store experimental feature is enabled. For example, include the following in nix.conf:

extra-experimental-features = mounted-ssh-store

Store URL format: mounted-ssh-ng://[username@]hostname

Experimental store type that allows full access to a Nix store on a remote machine, and additionally requires that store be mounted in the local file system.

The mounting of that store is not managed by Nix, and must by managed manually. It could be accomplished with SSHFS or NFS, for example.

The local file system is used to optimize certain operations. For example, rather than serializing Nix archives and sending over the Nix channel, we can directly access the file system data via the mount-point.

The local file system is also used to make certain operations possible that wouldn't otherwise be. For example, persistent GC roots can be created if they reside on the same file system as the remote store: the remote side will create the symlinks necessary to avoid race conditions.

Settings

  • base64-ssh-public-host-key

    The public host key of the remote machine.

    Default: empty

  • compress

    Whether to enable SSH compression.

    Default: false

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • max-connection-age

    Maximum age of a connection before it is closed.

    Default: 4294967295

  • max-connections

    Maximum number of concurrent connections to the Nix daemon.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • remote-program

    Path to the nix-daemon executable on the remote machine.

    Default: nix-daemon

  • remote-store

    Store URL to be used on the remote machine. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Default: empty

  • root

    Directory prefixed to all other paths.

    Default: ``

  • ssh-key

    Path to the SSH private key used to authenticate to the remote machine.

    Default: empty

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Experimental SSH Store

Store URL format: ssh-ng://[username@]hostname

Experimental store type that allows full access to a Nix store on a remote machine.

Settings

  • base64-ssh-public-host-key

    The public host key of the remote machine.

    Default: empty

  • compress

    Whether to enable SSH compression.

    Default: false

  • max-connection-age

    Maximum age of a connection before it is closed.

    Default: 4294967295

  • max-connections

    Maximum number of concurrent connections to the Nix daemon.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • remote-program

    Path to the nix-daemon executable on the remote machine.

    Default: nix-daemon

  • remote-store

    Store URL to be used on the remote machine. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Default: empty

  • ssh-key

    Path to the SSH private key used to authenticate to the remote machine.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

HTTP Binary Cache Store

Store URL format: http://..., https://...

This store allows a binary cache to be accessed via the HTTP protocol.

Settings

  • compression

    NAR compression method (xz, bzip2, gzip, zstd, or none).

    Default: xz

  • compression-level

    The preset level to be used when compressing NARs. The meaning and accepted values depend on the compression method selected. -1 specifies that the default compression level should be used.

    Default: -1

  • index-debug-info

    Whether to index DWARF debug info files by build ID. This allows dwarffs to fetch debug info on demand

    Default: false

  • local-nar-cache

    Path to a local cache of NARs fetched from this binary cache, used by commands such as nix store cat.

    Default: empty

  • parallel-compression

    Enable multi-threaded compression of NARs. This is currently only available for xz and zstd.

    Default: false

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • secret-key

    Path to the secret key used to sign the binary cache.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

  • write-nar-listing

    Whether to write a JSON file that lists the files in each NAR.

    Default: false

Local Binary Cache Store

Store URL format: file://path

This store allows reading and writing a binary cache stored in path in the local filesystem. If path does not exist, it will be created.

For example, the following builds or downloads nixpkgs#hello into the local store and then copies it to the binary cache in /tmp/binary-cache:

# nix copy --to file:///tmp/binary-cache nixpkgs#hello

Settings

  • compression

    NAR compression method (xz, bzip2, gzip, zstd, or none).

    Default: xz

  • compression-level

    The preset level to be used when compressing NARs. The meaning and accepted values depend on the compression method selected. -1 specifies that the default compression level should be used.

    Default: -1

  • index-debug-info

    Whether to index DWARF debug info files by build ID. This allows dwarffs to fetch debug info on demand

    Default: false

  • local-nar-cache

    Path to a local cache of NARs fetched from this binary cache, used by commands such as nix store cat.

    Default: empty

  • parallel-compression

    Enable multi-threaded compression of NARs. This is currently only available for xz and zstd.

    Default: false

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • secret-key

    Path to the secret key used to sign the binary cache.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

  • write-nar-listing

    Whether to write a JSON file that lists the files in each NAR.

    Default: false

Local Daemon Store

Store URL format: daemon, unix://path

This store type accesses a Nix store by talking to a Nix daemon listening on the Unix domain socket path. The store pseudo-URL daemon is equivalent to unix:///nix/var/nix/daemon-socket/socket.

Settings

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • max-connection-age

    Maximum age of a connection before it is closed.

    Default: 4294967295

  • max-connections

    Maximum number of concurrent connections to the Nix daemon.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • root

    Directory prefixed to all other paths.

    Default: ``

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Local Store

Store URL format: local, root

This store type accesses a Nix store in the local filesystem directly (i.e. not via the Nix daemon). root is an absolute path that is prefixed to other directories such as the Nix store directory. The store pseudo-URL local denotes a store that uses / as its root directory.

A store that uses a root other than / is called a chroot store. With such stores, the store directory is "logically" still /nix/store, so programs stored in them can only be built and executed by chroot-ing into root. Chroot stores only support building and running on Linux when mount namespaces and user namespaces are enabled.

For example, the following uses /tmp/root as the chroot environment to build or download nixpkgs#hello and then execute it:

# nix run --store /tmp/root nixpkgs#hello
Hello, world!

Here, the "physical" store location is /tmp/root/nix/store, and Nix's store metadata is in /tmp/root/nix/var/nix/db.

It is also possible, but not recommended, to change the "logical" location of the Nix store from its default of /nix/store. This makes it impossible to use default substituters such as https://cache.nixos.org/, and thus you may have to build everything locally. Here is an example:

# nix build --store 'local?store=/tmp/my-nix/store&state=/tmp/my-nix/state&log=/tmp/my-nix/log' nixpkgs#hello

Settings

  • log

    directory where Nix will store log files.

    Default: /nix/var/log/nix

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • read-only

    Allow this store to be opened when its database is on a read-only filesystem.

    Normally Nix will attempt to open the store database in read-write mode, even for querying (when write access is not needed), causing it to fail if the database is on a read-only filesystem.

    Enable read-only mode to disable locking and open the SQLite database with the immutable parameter set.

    Warning Do not use this unless the filesystem is read-only.

    Using it when the filesystem is writable can cause incorrect query results or corruption errors if the database is changed by another process. While the filesystem the database resides on might appear to be read-only, consider whether another user or system might have write access to it.

    Default: false

  • real

    Physical path of the Nix store.

    Default: /nix/store

  • require-sigs

    Whether store paths copied into this store should have a trusted signature.

    Default: true

  • root

    Directory prefixed to all other paths.

    Default: ``

  • state

    Directory where Nix will store state.

    Default: /dummy

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

S3 Binary Cache Store

Store URL format: s3://bucket-name

This store allows reading and writing a binary cache stored in an AWS S3 (or S3-compatible service) bucket. This store shares many idioms with the HTTP Binary Cache Store.

For AWS S3, the binary cache URL for a bucket named example-nix-cache will be exactly s3://example-nix-cache. For S3 compatible binary caches, consult that cache's documentation.

Anonymous reads to your S3-compatible binary cache

If your binary cache is publicly accessible and does not require authentication, it is simplest to use the [HTTP Binary Cache Store] rather than S3 Binary Cache Store with https://example-nix-cache.s3.amazonaws.com instead of s3://example-nix-cache.

Your bucket will need a bucket policy like the following to be accessible:

{
    "Id": "DirectReads",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowDirectReads",
            "Action": [
                "s3:GetObject",
                "s3:GetBucketLocation"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::example-nix-cache",
                "arn:aws:s3:::example-nix-cache/*"
            ],
            "Principal": "*"
        }
    ]
}

Authentication

Nix will use the default credential provider chain for authenticating requests to Amazon S3.

Note that this means Nix will read environment variables and files with different idioms than with Nix's own settings, as implemented by the AWS SDK. Consult the documentation linked above for further details.

Authenticated reads to your S3 binary cache

Your bucket will need a bucket policy allowing the desired users to perform the s3:GetObject and s3:GetBucketLocation action on all objects in the bucket. The anonymous policy given above can be updated to have a restricted Principal to support this.

Authenticated writes to your S3-compatible binary cache

Your account will need an IAM policy to support uploading to the bucket:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "UploadToCache",
      "Effect": "Allow",
      "Action": [
        "s3:AbortMultipartUpload",
        "s3:GetBucketLocation",
        "s3:GetObject",
        "s3:ListBucket",
        "s3:ListBucketMultipartUploads",
        "s3:ListMultipartUploadParts",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::example-nix-cache",
        "arn:aws:s3:::example-nix-cache/*"
      ]
    }
  ]
}

Examples

With bucket policies and authentication set up as described above, uploading works via nix copy (experimental).

  • To upload with a specific credential profile for Amazon S3:

    $ nix copy nixpkgs.hello \
      --to 's3://example-nix-cache?profile=cache-upload&region=eu-west-2'
    
  • To upload to an S3-compatible binary cache:

    $ nix copy nixpkgs.hello --to \
      's3://example-nix-cache?profile=cache-upload&scheme=https&endpoint=minio.example.com'
    

Settings

  • buffer-size

    Size (in bytes) of each part in multi-part uploads.

    Default: 5242880

  • compression

    NAR compression method (xz, bzip2, gzip, zstd, or none).

    Default: xz

  • compression-level

    The preset level to be used when compressing NARs. The meaning and accepted values depend on the compression method selected. -1 specifies that the default compression level should be used.

    Default: -1

  • endpoint

    The URL of the endpoint of an S3-compatible service such as MinIO. Do not specify this setting if you're using Amazon S3.

    Note

    This endpoint must support HTTPS and will use path-based addressing instead of virtual host based addressing.

    Default: empty

  • index-debug-info

    Whether to index DWARF debug info files by build ID. This allows dwarffs to fetch debug info on demand

    Default: false

  • local-nar-cache

    Path to a local cache of NARs fetched from this binary cache, used by commands such as nix store cat.

    Default: empty

  • log-compression

    Compression method for log/* files. It is recommended to use a compression method supported by most web browsers (e.g. brotli).

    Default: empty

  • ls-compression

    Compression method for .ls files.

    Default: empty

  • multipart-upload

    Whether to use multi-part uploads.

    Default: false

  • narinfo-compression

    Compression method for .narinfo files.

    Default: empty

  • parallel-compression

    Enable multi-threaded compression of NARs. This is currently only available for xz and zstd.

    Default: false

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • profile

    The name of the AWS configuration profile to use. By default Nix will use the default profile.

    Default: empty

  • region

    The region of the S3 bucket. If your bucket is not in us–east-1, you should always explicitly specify the region parameter.

    Default: us-east-1

  • scheme

    The scheme used for S3 requests, https (default) or http. This option allows you to disable HTTPS for binary caches which don't support it.

    Note

    HTTPS should be used if the cache might contain sensitive information.

    Default: empty

  • secret-key

    Path to the secret key used to sign the binary cache.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

  • write-nar-listing

    Whether to write a JSON file that lists the files in each NAR.

    Default: false

SSH Store

Store URL format: ssh://[username@]hostname

This store type allows limited access to a remote store on another machine via SSH.

Settings

  • base64-ssh-public-host-key

    The public host key of the remote machine.

    Default: empty

  • compress

    Whether to enable SSH compression.

    Default: false

  • max-connections

    Maximum number of concurrent SSH connections.

    Default: 1

  • path-info-cache-size

    Size of the in-memory store path metadata cache.

    Default: 65536

  • priority

    Priority of this store when used as a substituter. A lower value means a higher priority.

    Default: 0

  • remote-program

    Path to the nix-store executable on the remote machine.

    Default: nix-store

  • remote-store

    Store URL to be used on the remote machine. The default is auto (i.e. use the Nix daemon or /nix/store directly).

    Default: empty

  • ssh-key

    Path to the SSH private key used to authenticate to the remote machine.

    Default: empty

  • store

    Logical location of the Nix store, usually /nix/store. Note that you can only copy store paths between stores if they have the same store setting.

    Default: /nix/store

  • system-features

    Optional system features available on the system this store uses to build derivations.

    Example: "kvm"

    Default: machine-specific

  • trusted

    Whether paths from this store can be used as substitutes even if they are not signed by a key listed in the trusted-public-keys setting.

    Default: false

  • want-mass-query

    Whether this store can be queried efficiently for path validity when used as a substituter.

    Default: false

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix key - generate and convert Nix signing keys

Synopsis

nix key [option...] subcommand

where subcommand is one of the following:

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix key convert-secret-to-public - generate a public key for verifying store paths from a secret key read from standard input

Synopsis

nix key convert-secret-to-public [option...]

Examples

  • Convert a secret key to a public key:

    # echo cache.example.org-0:E7lAO+MsPwTFfPXsdPtW8GKui/5ho4KQHVcAGnX+Tti1V4dUxoVoqLyWJ4YESuZJwQ67GVIksDt47og+tPVUZw== \
      | nix key convert-secret-to-public
    cache.example.org-0:tVeHVMaFaKi8lieGBErmScEOuxlSJLA7eO6IPrT1VGc=
    

Description

This command reads a Ed25519 secret key from standard input, and writes the corresponding public key to standard output. For more details, see nix key generate-secret.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix key generate-secret - generate a secret key for signing store paths

Synopsis

nix key generate-secret [option...]

Examples

  • Generate a new secret key:

    # nix key generate-secret --key-name cache.example.org-1 > ./secret-key
    

    We can then use this key to sign the closure of the Hello package:

    # nix build nixpkgs#hello
    # nix store sign --key-file ./secret-key --recursive ./result
    

    Finally, we can verify the store paths using the corresponding public key:

    # nix store verify --trusted-public-keys $(nix key convert-secret-to-public < ./secret-key) ./result
    

Description

This command generates a new Ed25519 secret key for signing store paths and prints it on standard output. Use nix key convert-secret-to-public to get the corresponding public key for verifying signed store paths.

The mandatory argument --key-name specifies a key name (such as cache.example.org-1). It 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).

Format

Both secret and public keys are represented as the key name followed by a base-64 encoding of the Ed25519 key data, e.g.

cache.example.org-0:E7lAO+MsPwTFfPXsdPtW8GKui/5ho4KQHVcAGnX+Tti1V4dUxoVoqLyWJ4YESuZJwQ67GVIksDt47og+tPVUZw==

Options

  • --key-name name

    Identifier of the key (e.g. cache.example.org-1).

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix log - show the build log of the specified packages or paths, if available

Synopsis

nix log [option...] installable

Examples

  • Get the build log of GNU Hello:

    # nix log nixpkgs#hello
    
  • Get the build log of a specific store path:

    # nix log /nix/store/lmngj4wcm9rkv3w4dfhzhcyij3195hiq-thunderbird-52.2.1
    
  • Get a build log from a specific binary cache:

    # nix log --store https://cache.nixos.org nixpkgs#hello
    

Description

This command prints the log of a previous build of the installable on standard output.

Nix looks for build logs in two places:

  • In the directory /nix/var/log/nix/drvs, which contains logs for locally built derivations.

  • In the binary caches listed in the substituters setting. Logs should be named <cache>/log/<base-name-of-store-path>, where store-path is a derivation, e.g. https://cache.nixos.org/log/dvmig8jgrdapvbyxb1rprckdmdqx08kv-hello-2.10.drv. For non-derivation store paths, Nix will first try to determine the deriver by fetching the .narinfo file for this store path.

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix nar - create or inspect NAR files

Synopsis

nix nar [option...] subcommand

where subcommand is one of the following:

  • nix nar cat - print the contents of a file inside a NAR file on stdout
  • nix nar dump-path - serialise a path to stdout in NAR format
  • nix nar ls - show information about a path inside a NAR file
  • nix nar pack - serialise a path to stdout in NAR format

Description

nix nar provides several subcommands for creating and inspecting Nix Archives (NARs).

File format

For the definition of the Nix Archive file format, see within the protocols chapter of the manual.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix nar cat - print the contents of a file inside a NAR file on stdout

Synopsis

nix nar cat [option...] nar path

Examples

  • List a file in a Nix Archive (NAR) and pipe it through gunzip:

    # nix nar cat ./hello.nar /share/man/man1/hello.1.gz | gunzip
    .\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.46.4.
    .TH HELLO "1" "November 2014" "hello 2.10" "User Commands"
    …
    

Description

This command prints on standard output the contents of the regular file path inside the NAR file nar.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix nar dump-path - serialise a path to stdout in NAR format

Synopsis

nix nar dump-path [option...] path

Examples

Description

This command generates a Nix Archive (NAR) file containing the serialisation of path, which must contain only regular files, directories and symbolic links. The NAR is written to standard output.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix nar ls - show information about a path inside a NAR file

Synopsis

nix nar ls [option...] nar path

Examples

  • To list a specific file in a NAR:

    # nix nar ls --long ./hello.nar /bin/hello
    -r-xr-xr-x                38184 hello
    
  • To recursively list the contents of a directory inside a NAR, in JSON format:

    # nix nar ls --json --recursive ./hello.nar /bin
    {"type":"directory","entries":{"hello":{"type":"regular","size":38184,"executable":true,"narOffset":400}}}
    

Description

This command shows information about a path inside Nix Archive (NAR) file nar.

Options

  • --directory / -d

    Show directories rather than their contents.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --long / -l

    Show detailed file information.

  • --recursive / -R

    List subdirectories recursively.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix nar pack - serialise a path to stdout in NAR format

Synopsis

nix nar pack [option...] path

Examples

Description

This command generates a Nix Archive (NAR) file containing the serialisation of path, which must contain only regular files, directories and symbolic links. The NAR is written to standard output.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix path-info - query information about store paths

Synopsis

nix path-info [option...] installables...

Examples

  • Print the store path produced by nixpkgs#hello:

    # nix path-info nixpkgs#hello
    /nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10
    
  • Show the closure sizes of every path in the current NixOS system closure, sorted by size:

    # nix path-info --recursive --closure-size /run/current-system | sort -nk2
    /nix/store/hl5xwp9kdrd1zkm0idm3kkby9q66z404-empty                                                96
    /nix/store/27324qvqhnxj3rncazmxc4mwy79kz8ha-nameservers                                         112
    …
    /nix/store/539jkw9a8dyry7clcv60gk6na816j7y8-etc                                          5783255504
    /nix/store/zqamz3cz4dbzfihki2mk7a63mbkxz9xq-nixos-system-machine-20.09.20201112.3090c65  5887562256
    
  • Show a package's closure size and all its dependencies with human readable sizes:

    # nix path-info --recursive --size --closure-size --human-readable nixpkgs#rustc
    /nix/store/01rrgsg5zk3cds0xgdsq40zpk6g51dz9-ncurses-6.2-dev      386.7 KiB   69.1 MiB
    /nix/store/0q783wnvixpqz6dxjp16nw296avgczam-libpfm-4.11.0          5.9 MiB   37.4 MiB
    …
    
  • Check the existence of a path in a binary cache:

    # nix path-info --recursive /nix/store/blzxgyvrk32ki6xga10phr4sby2xf25q-geeqie-1.5.1 --store https://cache.nixos.org/
    path '/nix/store/blzxgyvrk32ki6xga10phr4sby2xf25q-geeqie-1.5.1' is not valid
    
    
  • Print the 10 most recently added paths (using --json and the jq(1) command):

    # nix path-info --json --all | jq -r 'to_entries | sort_by(.value.registrationTime) | .[-11:-1][] | .key'
    
  • Show the size of the entire Nix store:

    # nix path-info --json --all | jq 'map(.narSize) | add'
    49812020936
    
  • Show every path whose closure is bigger than 1 GB, sorted by closure size:

    # nix path-info --json --all --closure-size \
      | jq 'map_values(.closureSize | select(. < 1e9)) | to_entries | sort_by(.value)'
    [
      …,
      {
        .key = "/nix/store/zqamz3cz4dbzfihki2mk7a63mbkxz9xq-nixos-system-machine-20.09.20201112.3090c65",
        .value = 5887562256,
      }
    ]
    
  • Print the path of the store derivation produced by nixpkgs#hello:

    # nix path-info --derivation nixpkgs#hello
    /nix/store/s6rn4jz1sin56rf4qj5b5v8jxjm32hlk-hello-2.10.drv
    

Description

This command shows information about the store paths produced by installables, or about all paths in the store if you pass --all.

By default, this command only prints the store paths. You can get additional information by passing flags such as --closure-size, --size, --sigs or --json.

Warning

Note that nix path-info does not build or substitute the installables you specify. Thus, if the corresponding store paths don't already exist, this command will fail. You can use nix build to ensure that they exist.

Options

  • --closure-size / -S

    Print the sum of the sizes of the NAR serialisations of the closure of each path.

  • --human-readable / -h

    With -s and -S, print sizes in a human-friendly format such as 5.67G.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --sigs

    Show signatures.

  • --size / -s

    Print the size of the NAR serialisation of each path.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix print-dev-env - print shell code that can be sourced by bash to reproduce the build environment of a derivation

Synopsis

nix print-dev-env [option...] installable

Examples

  • Apply the build environment of GNU hello to the current shell:

    # . <(nix print-dev-env nixpkgs#hello)
    
  • Get the build environment in JSON format:

    # nix print-dev-env nixpkgs#hello --json
    

    The output will look like this:

    {
      "bashFunctions": {
        "buildPhase": " \n    runHook preBuild;\n...",
        ...
      },
      "variables": {
        "src": {
          "type": "exported",
          "value": "/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz"
        },
        "postUnpackHooks": {
          "type": "array",
          "value": ["_updateSourceDateEpochFromSourceRoot"]
        },
        ...
      }
    }
    

Description

This command prints a shell script that can be sourced by bash and that sets the variables and shell functions defined by the build process of installable. This allows you to get a similar build environment in your current shell rather than in a subshell (as with nix develop).

With --json, the output is a JSON serialisation of the variables and functions defined by the build process.

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --profile path

    The profile to operate on.

  • --redirect installable outputs-dir

    Redirect a store path to a mutable location.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile - manage Nix profiles

Synopsis

nix profile [option...] subcommand

where subcommand is one of the following:

Description

nix profile allows you to create and manage Nix profiles. A Nix profile is a set of packages that can be installed and upgraded independently from each other. Nix profiles are versioned, allowing them to be rolled back easily.

Files

Profiles

A directory that contains links to profiles managed by nix-env and nix profile:

  • $XDG_STATE_HOME/nix/profiles for regular users
  • $NIX_STATE_DIR/profiles/per-user/root if the user is root

A profile is a directory of symlinks to files in the Nix store.

Filesystem layout

Profiles are versioned as follows. When using a profile named path, path is a symlink to path-N-link, where N is the version of the profile. In turn, path-N-link is a symlink to a path in the Nix store. For example:

$ ls -l ~alice/.local/state/nix/profiles/profile*
lrwxrwxrwx 1 alice users 14 Nov 25 14:35 /home/alice/.local/state/nix/profiles/profile -> profile-7-link
lrwxrwxrwx 1 alice users 51 Oct 28 16:18 /home/alice/.local/state/nix/profiles/profile-5-link -> /nix/store/q69xad13ghpf7ir87h0b2gd28lafjj1j-profile
lrwxrwxrwx 1 alice users 51 Oct 29 13:20 /home/alice/.local/state/nix/profiles/profile-6-link -> /nix/store/6bvhpysd7vwz7k3b0pndn7ifi5xr32dg-profile
lrwxrwxrwx 1 alice users 51 Nov 25 14:35 /home/alice/.local/state/nix/profiles/profile-7-link -> /nix/store/mp0x6xnsg0b8qhswy6riqvimai4gm677-profile

Each of these symlinks is a root for the Nix garbage collector.

The contents of the store path corresponding to each version of the profile is a tree of symlinks to the files of the installed packages, e.g.

$ ll -R ~eelco/.local/state/nix/profiles/profile-7-link/
/home/eelco/.local/state/nix/profiles/profile-7-link/:
total 20
dr-xr-xr-x 2 root root 4096 Jan  1  1970 bin
-r--r--r-- 2 root root 1402 Jan  1  1970 manifest.nix
dr-xr-xr-x 4 root root 4096 Jan  1  1970 share

/home/eelco/.local/state/nix/profiles/profile-7-link/bin:
total 20
lrwxrwxrwx 5 root root 79 Jan  1  1970 chromium -> /nix/store/ijm5k0zqisvkdwjkc77mb9qzb35xfi4m-chromium-86.0.4240.111/bin/chromium
lrwxrwxrwx 7 root root 87 Jan  1  1970 spotify -> /nix/store/w9182874m1bl56smps3m5zjj36jhp3rn-spotify-1.1.26.501.gbe11e53b-15/bin/spotify
lrwxrwxrwx 3 root root 79 Jan  1  1970 zoom-us -> /nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927/bin/zoom-us

/home/eelco/.local/state/nix/profiles/profile-7-link/share/applications:
total 12
lrwxrwxrwx 4 root root 120 Jan  1  1970 chromium-browser.desktop -> /nix/store/4cf803y4vzfm3gyk3vzhzb2327v0kl8a-chromium-unwrapped-86.0.4240.111/share/applications/chromium-browser.desktop
lrwxrwxrwx 7 root root 110 Jan  1  1970 spotify.desktop -> /nix/store/w9182874m1bl56smps3m5zjj36jhp3rn-spotify-1.1.26.501.gbe11e53b-15/share/applications/spotify.desktop
lrwxrwxrwx 3 root root 107 Jan  1  1970 us.zoom.Zoom.desktop -> /nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927/share/applications/us.zoom.Zoom.desktop

…

Each profile version contains a manifest file:

A symbolic link to the user's current profile:

By default, this symlink points to:

  • $XDG_STATE_HOME/nix/profiles/profile for regular users
  • $NIX_STATE_DIR/profiles/per-user/root/profile for root

The PATH environment variable should include /bin subdirectory of the profile link (e.g. ~/.nix-profile/bin) for the user environment to be visible to the user. The installer sets this up by default, unless you enable use-xdg-base-directories.

Profile compatibility

Warning

Once you have used nix profile you can no longer use nix-env without first deleting $XDG_STATE_HOME/nix/profiles/profile

Once you installed a package with nix profile, you get the following error message when using nix-env:

$ nix-env -f '<nixpkgs>' -iA 'hello'
error: nix-env
profile '/home/alice/.local/state/nix/profiles/profile' is incompatible with 'nix-env'; please use 'nix profile' instead

To migrate back to nix-env you can delete your current profile:

Warning

This will delete packages that have been installed before, so you may want to back up this information before running the command.

 $ rm -rf "${XDG_STATE_HOME-$HOME/.local/state}/nix/profiles/profile"

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile diff-closures - show the closure difference between each version of a profile

Synopsis

nix profile diff-closures [option...]

Examples

  • Show what changed between each version of the NixOS system profile:

    # nix profile diff-closures --profile /nix/var/nix/profiles/system
    Version 13 -> 14:
      acpi-call: 2020-04-07-5.8.13 → 2020-04-07-5.8.14
      aws-sdk-cpp: -6723.1 KiB
      …
    
    Version 14 -> 15:
      acpi-call: 2020-04-07-5.8.14 → 2020-04-07-5.8.16
      attica: -996.2 KiB
      breeze-icons: -78713.5 KiB
      brotli: 1.0.7 → 1.0.9, +44.2 KiB
    

Description

This command shows the difference between the closures of subsequent versions of a profile. See nix store diff-closures for details.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile history - show all versions of a profile

Synopsis

nix profile history [option...]

Examples

  • Show the changes between each version of your default profile:

    # nix profile history
    Version 508 (2020-04-10):
      flake:nixpkgs#legacyPackages.x86_64-linux.awscli: ∅ -> 1.17.13
    
    Version 509 (2020-05-16) <- 508:
      flake:nixpkgs#legacyPackages.x86_64-linux.awscli: 1.17.13 -> 1.18.211
    

Description

This command shows what packages were added, removed or upgraded between subsequent versions of a profile. It only shows top-level packages, not dependencies; for that, use nix profile diff-closures.

The addition of a package to a profile is denoted by the string ∅ -> version, whereas the removal is denoted by version -> ∅.

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile install - install a package into a profile

Synopsis

nix profile install [option...] installables...

Examples

  • Install a package from Nixpkgs:

    # nix profile install nixpkgs#hello
    
  • Install a package from a specific branch of Nixpkgs:

    # nix profile install nixpkgs/release-20.09#hello
    
  • Install a package from a specific revision of Nixpkgs:

    # nix profile install nixpkgs/d73407e8e6002646acfdef0e39ace088bacc83da#hello
    
  • Install a specific output of a package:

    # nix profile install nixpkgs#bash^man
    

Description

This command adds installables to a Nix profile.

Options

  • --priority priority

    The priority of the package to install.

  • --profile path

    The profile to operate on.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile list - list installed packages

Synopsis

nix profile list [option...]

Examples

  • Show what packages are installed in the default profile:

    # nix profile list
    Name:               gdb
    Flake attribute:    legacyPackages.x86_64-linux.gdb
    Original flake URL: flake:nixpkgs
    Locked flake URL:   github:NixOS/nixpkgs/7b38b03d76ab71bdc8dc325e3f6338d984cc35ca
    Store paths:        /nix/store/indzcw5wvlhx6vwk7k4iq29q15chvr3d-gdb-11.1
    
    Name:               blender-bin
    Flake attribute:    packages.x86_64-linux.default
    Original flake URL: flake:blender-bin
    Locked flake URL:   github:edolstra/nix-warez/91f2ffee657bf834e4475865ae336e2379282d34?dir=blender
    Store paths:        /nix/store/i798sxl3j40wpdi1rgf391id1b5klw7g-blender-bin-3.1.2
    

    Note that you can unambiguously rebuild a package from a profile through its locked flake URL and flake attribute, e.g.

    # nix build github:edolstra/nix-warez/91f2ffee657bf834e4475865ae336e2379282d34?dir=blender#packages.x86_64-linux.default
    

    will build the package blender-bin shown above.

Description

This command shows what packages are currently installed in a profile. For each installed package, it shows the following information:

  • Name: A unique name used to unambiguously identify the package in invocations of nix profile remove and nix profile upgrade.

  • Index: An integer that can be used to unambiguously identify the package in invocations of nix profile remove and nix profile upgrade. (Deprecated, will be removed in a future version in favor of Name.)

  • Flake attribute: The flake output attribute path that provides the package (e.g. packages.x86_64-linux.hello).

  • Original flake URL: The original ("unlocked") flake reference specified by the user when the package was first installed via nix profile install.

  • Locked flake URL: The locked flake reference to which the original flake reference was resolved.

  • Store paths: The store path(s) of the package.

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --profile path

    The profile to operate on.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile remove - remove packages from a profile

Synopsis

nix profile remove [option...] elements...

Examples

  • Remove a package by name:

    # nix profile remove hello
    
  • Remove all packages:

    # nix profile remove --all
    
  • Remove packages by regular expression:

    # nix profile remove --regex '.*vim.*'
    
  • Remove a package by store path:

    # nix profile remove /nix/store/rr3y0c6zyk7kjjl8y19s4lsrhn4aiq1z-hello-2.10
    

Description

This command removes a package from a profile.

Options

  • --all

    Match all packages in the profile.

  • --profile path

    The profile to operate on.

  • --regex pattern

    A regular expression to match one or more packages in the profile.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile rollback - roll back to the previous version or a specified version of a profile

Synopsis

nix profile rollback [option...]

Examples

  • Roll back your default profile to the previous version:

    # nix profile rollback
    switching profile from version 519 to 518
    
  • Switch your default profile to version 510:

    # nix profile rollback --to 510
    switching profile from version 518 to 510
    

Description

This command switches a profile to the most recent version older than the currently active version, or if --to N is given, to version N of the profile. To see the available versions of a profile, use nix profile history.

Options

  • --dry-run

    Show what this command would do without doing it.

  • --profile path

    The profile to operate on.

  • --to version

    The profile version to roll back to.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile upgrade - upgrade packages using their most recent flake

Synopsis

nix profile upgrade [option...] elements...

Examples

  • Upgrade all packages that were installed using an unlocked flake reference:

    # nix profile upgrade --all
    
  • Upgrade a specific package by name:

    # nix profile upgrade hello
    
  • Upgrade all packages that include 'vim' in their name:

    # nix profile upgrade --regex '.*vim.*'
    

Description

This command upgrades a previously installed package in a Nix profile, by fetching and evaluating the latest version of the flake from which the package was installed.

Warning

This only works if you used an unlocked flake reference at installation time, e.g. nixpkgs#hello. It does not work if you used a locked flake reference (e.g. github:NixOS/nixpkgs/13d0c311e3ae923a00f734b43fd1d35b47d8943a#hello), since in that case the "latest version" is always the same.

Options

  • --all

    Match all packages in the profile.

  • --profile path

    The profile to operate on.

  • --regex pattern

    A regular expression to match one or more packages in the profile.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix profile wipe-history - delete non-current versions of a profile

Synopsis

nix profile wipe-history [option...]

Examples

  • Delete all versions of the default profile older than 100 days:

    # nix profile wipe-history --profile /tmp/profile --older-than 100d
    removing profile version 515
    removing profile version 514
    

Description

This command deletes non-current versions of a profile, making it impossible to roll back to these versions. By default, all non-current versions are deleted. With --older-than Nd, all non-current versions older than N days are deleted.

Options

  • --dry-run

    Show what this command would do without doing it.

  • --older-than age

    Delete versions older than the specified age. age must be in the format Nd, where N denotes a number of days.

  • --profile path

    The profile to operate on.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix realisation - manipulate a Nix realisation

Synopsis

nix realisation [option...] subcommand

where subcommand is one of the following:

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix realisation info - query information about one or several realisations

Synopsis

nix realisation info [option...] installables...

Description

Display some information about the given realisation

Examples

Show some information about the realisation of the hello package:

$ nix realisation info nixpkgs#hello --json
[{"id":"sha256:3d382378a00588e064ee30be96dd0fa7e7df7cf3fbcace85a0e7b7dada1eef25!out","outPath":"fd3m7xawvrqcg98kgz5hc2vk3x9q0lh7-hello"}]

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix registry - manage the flake registry

Synopsis

nix registry [option...] subcommand

where subcommand is one of the following:

Description

nix registry provides subcommands for managing flake registries. Flake registries are a convenience feature that allows you to refer to flakes using symbolic identifiers such as nixpkgs, rather than full URLs such as git://github.com/NixOS/nixpkgs. You can use these identifiers on the command line (e.g. when you do nix run nixpkgs#hello) or in flake input specifications in flake.nix files. The latter are automatically resolved to full URLs and recorded in the flake's flake.lock file.

In addition, the flake registry allows you to redirect arbitrary flake references (e.g. github:NixOS/patchelf) to another location, such as a local fork.

There are multiple registries. These are, in order from lowest to highest precedence:

  • The global registry, which is a file downloaded from the URL specified by the setting flake-registry. It is cached locally and updated automatically when it's older than tarball-ttl seconds. The default global registry is kept in a GitHub repository.

  • The system registry, which is shared by all users. The default location is /etc/nix/registry.json. On NixOS, the system registry can be specified using the NixOS option nix.registry.

  • The user registry ~/.config/nix/registry.json. This registry can be modified by commands such as nix registry pin.

  • Overrides specified on the command line using the option --override-flake.

Note that the system and user registries are not used to resolve flake references in flake.nix. They are only used to resolve flake references on the command line.

Registry format

A registry is a JSON file with the following format:

{
  "version": 2,
  "flakes": [
    {
      "from": {
        "type": "indirect",
        "id": "nixpkgs"
      },
      "to": {
        "type": "github",
        "owner": "NixOS",
        "repo": "nixpkgs"
      }
    },
    ...
  ]
}

That is, it contains a list of objects with attributes from and to, both of which contain a flake reference in attribute representation. (For example, {"type": "indirect", "id": "nixpkgs"} is the attribute representation of nixpkgs, while {"type": "github", "owner": "NixOS", "repo": "nixpkgs"} is the attribute representation of github:NixOS/nixpkgs.)

Given some flake reference R, a registry entry is used if its from flake reference matches R. R is then replaced by the unification of the to flake reference with R.

Matching

The from flake reference in a registry entry matches some flake reference R if the attributes in from are the same as the attributes in R. For example:

  • nixpkgs matches with nixpkgs.

  • nixpkgs matches with nixpkgs/nixos-20.09.

  • nixpkgs/nixos-20.09 does not match with nixpkgs.

  • nixpkgs does not match with git://github.com/NixOS/patchelf.

Unification

The to flake reference in a registry entry is unified with some flake reference R by taking to and applying the rev and ref attributes from R, if specified. For example:

  • github:NixOS/nixpkgs unified with nixpkgs produces github:NixOS/nixpkgs.

  • github:NixOS/nixpkgs unified with nixpkgs/nixos-20.09 produces github:NixOS/nixpkgs/nixos-20.09.

  • github:NixOS/nixpkgs/master unified with nixpkgs/nixos-20.09 produces github:NixOS/nixpkgs/nixos-20.09.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix registry add - add/replace flake in user flake registry

Synopsis

nix registry add [option...] from-url to-url

Examples

  • Set the nixpkgs flake identifier to a specific branch of Nixpkgs:

    # nix registry add nixpkgs github:NixOS/nixpkgs/nixos-20.03
    
  • Pin nixpkgs to a specific revision:

    # nix registry add nixpkgs github:NixOS/nixpkgs/925b70cd964ceaedee26fde9b19cc4c4f081196a
    
  • Add an entry that redirects a specific branch of nixpkgs to another fork:

    # nix registry add nixpkgs/nixos-20.03 ~/Dev/nixpkgs
    
  • Add nixpkgs pointing to github:nixos/nixpkgs to your custom flake registry:

    nix registry add --registry ./custom-flake-registry.json nixpkgs github:nixos/nixpkgs
    

Description

This command adds an entry to the user registry that maps flake reference from-url to flake reference to-url. If an entry for from-url already exists, it is overwritten.

Entries can be removed using nix registry remove.

Options

Common evaluation options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix registry list - list available Nix flakes

Synopsis

nix registry list [option...]

Examples

  • Show the contents of all registries:

    # nix registry list
    user   flake:dwarffs github:edolstra/dwarffs/d181d714fd36eb06f4992a1997cd5601e26db8f5
    system flake:nixpkgs path:/nix/store/fxl9mrm5xvzam0lxi9ygdmksskx4qq8s-source?lastModified=1605220118&narHash=sha256-Und10ixH1WuW0XHYMxxuHRohKYb45R%2fT8CwZuLd2D2Q=&rev=3090c65041104931adda7625d37fa874b2b5c124
    global flake:blender-bin github:edolstra/nix-warez?dir=blender
    global flake:dwarffs github:edolstra/dwarffs
    …
    

Description

This command displays the contents of all registries on standard output. Each line represents one registry entry in the format type from to, where type denotes the registry containing the entry:

  • flags: entries specified on the command line using --override-flake.
  • user: the user registry.
  • system: the system registry.
  • global: the global registry.

See the nix registry manual page for more details.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix registry pin - pin a flake to its current version or to the current version of a flake URL

Synopsis

nix registry pin [option...] url locked

Examples

  • Pin nixpkgs to its most recent Git revision:

    # nix registry pin nixpkgs
    

    Afterwards the user registry will have an entry like this:

    nix registry list | grep '^user '
    user   flake:nixpkgs github:NixOS/nixpkgs/925b70cd964ceaedee26fde9b19cc4c4f081196a
    

    and nix flake metadata will say:

    # nix flake metadata nixpkgs
    Resolved URL:  github:NixOS/nixpkgs/925b70cd964ceaedee26fde9b19cc4c4f081196a
    Locked URL:    github:NixOS/nixpkgs/925b70cd964ceaedee26fde9b19cc4c4f081196a
    …
    
  • Pin nixpkgs in a custom registry to its most recent Git revision:

    # nix registry pin --registry ./custom-flake-registry.json nixpkgs
    

Description

This command adds an entry to the user registry that maps flake reference url to the corresponding locked flake reference, that is, a flake reference that specifies an exact revision or content hash. This ensures that until this registry entry is removed, all uses of url will resolve to exactly the same flake.

Entries can be removed using nix registry remove.

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix registry remove - remove flake from user flake registry

Synopsis

nix registry remove [option...] url

Examples

  • Remove the entry nixpkgs from the user registry:

    # nix registry remove nixpkgs
    
  • Remove the entry nixpkgs from a custom registry:

    # nix registry remove --registry ./custom-flake-registry.json nixpkgs
    

Description

This command removes from the user registry any entry for flake reference url.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix repl - start an interactive environment for evaluating Nix expressions

Synopsis

nix repl [option...] installables...

Examples

  • Display all special commands within the REPL:

    # nix repl
    nix-repl> :?
    
  • Evaluate some simple Nix expressions:

    # nix repl
    
    nix-repl> 1 + 2
    3
    
    nix-repl> map (x: x * 2) [1 2 3]
    [ 2 4 6 ]
    
  • Interact with Nixpkgs in the REPL:

    # nix repl --file example.nix
    Loading Installable ''...
    Added 3 variables.
    
    # nix repl --expr '{a={b=3;c=4;};}'
    Loading Installable ''...
    Added 1 variables.
    
    # nix repl --expr '{a={b=3;c=4;};}' a
    Loading Installable ''...
    Added 1 variables.
    
    # nix repl nixpkgs
    Loading Installable 'flake:nixpkgs#'...
    Added 5 variables.
    
    nix-repl> legacyPackages.x86_64-linux.emacs.name
    "emacs-27.1"
    
    nix-repl> :q
    
    # nix repl --expr 'import <nixpkgs>{}'
    
    Loading Installable ''...
    Added 12439 variables.
    
    nix-repl> emacs.name
    "emacs-27.1"
    
    nix-repl> emacs.drvPath
    "/nix/store/lp0sjrhgg03y2n0l10n70rg0k7hhyz0l-emacs-27.1.drv"
    
    nix-repl> drv = runCommand "hello" { buildInputs = [ hello ]; } "hello; hello > $out"
    
    nix-repl> :b drv
    this derivation produced the following outputs:
      out -> /nix/store/0njwbgwmkwls0w5dv9mpc1pq5fj39q0l-hello
    
    nix-repl> builtins.readFile drv
    "Hello, world!\n"
    
    nix-repl> :log drv
    Hello, world!
    

Description

This command provides an interactive environment for evaluating Nix expressions. (REPL stands for 'read–eval–print loop'.)

On startup, it loads the Nix expressions named files and adds them into the lexical scope. You can load addition files using the :l <filename> command, or reload all files using :r.

Options

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix run - run a Nix application

Synopsis

nix run [option...] installable args...

Examples

  • Run the default app from the blender-bin flake:

    # nix run blender-bin
    
  • Run a non-default app from the blender-bin flake:

    # nix run blender-bin#blender_2_83
    

    Tip: you can find apps provided by this flake by running nix flake show blender-bin.

  • Run vim from the nixpkgs flake:

    # nix run nixpkgs#vim
    

    Note that vim (as of the time of writing of this page) is not an app but a package. Thus, Nix runs the eponymous file from the vim package.

  • Run vim with arguments:

    # nix run nixpkgs#vim -- --help
    

Description

nix run builds and runs installable, which must evaluate to an app or a regular Nix derivation.

If installable evaluates to an app (see below), it executes the program specified by the app definition.

If installable evaluates to a derivation, it will try to execute the program <out>/bin/<name>, where out is the primary output store path of the derivation, and name is the first of the following that exists:

  • The meta.mainProgram attribute of the derivation.
  • The pname attribute of the derivation.
  • The name part of the value of the name attribute of the derivation.

For instance, if name is set to hello-1.10, nix run will run $out/bin/hello.

Flake output attributes

If no flake output attribute is given, nix run tries the following flake output attributes:

  • apps.<system>.default

  • packages.<system>.default

If an attribute name is given, nix run tries the following flake output attributes:

  • apps.<system>.<name>

  • packages.<system>.<name>

  • legacyPackages.<system>.<name>

Apps

An app is specified by a flake output attribute named apps.<system>.<name>. It looks like this:

apps.x86_64-linux.blender_2_79 = {
  type = "app";
  program = "${self.packages.x86_64-linux.blender_2_79}/bin/blender";
  meta.description = "Run Blender, a free and open-source 3D creation suite.";
};

The only supported attributes are:

  • type (required): Must be set to app.

  • program (required): The full path of the executable to run. It must reside in the Nix store.

  • meta.description (optional): A description of the app.

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change environment variables

  • --ignore-env / -i

    Clear the entire environment, except for those specified with --keep-env-var.

  • --keep-env-var / -k name

    Keep the environment variable name, when using --ignore-env.

  • --set-env-var / -s name value

    Sets an environment variable name with value.

  • --unset-env-var / -u name

    Unset the environment variable name.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix search - search for packages

Synopsis

nix search [option...] installable regex...

Examples

  • Show all packages in the nixpkgs flake:

    # nix search nixpkgs ^
    * legacyPackages.x86_64-linux.AMB-plugins (0.8.1)
      A set of ambisonics ladspa plugins
    
    * legacyPackages.x86_64-linux.ArchiSteamFarm (4.3.1.0)
      Application with primary purpose of idling Steam cards from multiple accounts simultaneously
    …
    
  • Show packages in the nixpkgs flake containing blender in its name or description:

    # nix search nixpkgs blender
    * legacyPackages.x86_64-linux.blender (2.91.0)
      3D Creation/Animation/Publishing System
    
  • Search for packages underneath the attribute gnome3 in Nixpkgs:

    # nix search nixpkgs#gnome3 vala
    * legacyPackages.x86_64-linux.gnome3.vala (0.48.9)
      Compiler for GObject type system
    
  • Show all packages in the flake in the current directory:

    # nix search . ^
    
  • Search for Firefox or Chromium:

    # nix search nixpkgs 'firefox|chromium'
    
  • Search for packages containing git and either frontend or gui:

    # nix search nixpkgs git 'frontend|gui'
    
  • Search for packages containing neovim but hide ones containing either gui or python:

    # nix search nixpkgs neovim --exclude 'python|gui'
    

    or

    # nix search nixpkgs neovim --exclude 'python' --exclude 'gui'
    

Description

nix search searches installable that can be evaluated, that is, a flake or Nix expression, but not a store path or deriving path) for packages whose name or description matches all of the regular expressions regex. For each matching package, It prints the full attribute name (from the root of the installable), the version and the meta.description field, highlighting the substrings that were matched by the regular expressions.

To show all packages, use the regular expression ^. In contrast to .*, it avoids highlighting the entire name and description of every package.

Note that in this context, ^ is the regex character to match the beginning of a string, not the delimiter for selecting a derivation output.

Flake output attributes

If no flake output attribute is given, nix search searches for packages:

  • Directly underneath packages.<system>.

  • Underneath legacyPackages.<system>, recursing into attribute sets that contain an attribute recurseForDerivations = true.

Options

  • --exclude / -e regex

    Hide packages whose attribute path, name or description contain regex.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store - manipulate a Nix store

Synopsis

nix store [option...] subcommand

where subcommand is one of the following:

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store add - Add a file or directory to the Nix store

Synopsis

nix store add [option...] path

Description

Copy path to the Nix store, and print the resulting store path on standard output.

Warning

The resulting store path is not registered as a garbage collector root, so it could be deleted before you have a chance to register it.

Examples

Add a directory to the store:

# mkdir dir
# echo foo > dir/bar

# nix store add ./dir
/nix/store/6pmjx56pm94n66n4qw1nff0y1crm8nqg-dir

# cat /nix/store/6pmjx56pm94n66n4qw1nff0y1crm8nqg-dir/bar
foo

Options

  • --dry-run

    Show what this command would do without doing it.

  • --hash-algo hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --mode content-address-method

    How to compute the content-address of the store object. One of:

    • nar (the default): Serialises the input as a Nix Archive and passes that to the hash function.

    • flat: Assumes that the input is a single file and directly passes it to the hash function.

    • text: Like flat, but used for derivations serialized in store object and builtins.toFile. For advanced use-cases only; for regular usage prefer nar and flat.

  • --name / -n name

    Override the name component of the store path. It defaults to the base name of path.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store add-file - Deprecated. Use nix store add --mode flat instead.

Synopsis

nix store add-file [option...] path

Options

  • --dry-run

    Show what this command would do without doing it.

  • --hash-algo hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --mode content-address-method

    How to compute the content-address of the store object. One of:

    • nar (the default): Serialises the input as a Nix Archive and passes that to the hash function.

    • flat: Assumes that the input is a single file and directly passes it to the hash function.

    • text: Like flat, but used for derivations serialized in store object and builtins.toFile. For advanced use-cases only; for regular usage prefer nar and flat.

  • --name / -n name

    Override the name component of the store path. It defaults to the base name of path.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store add-path - Deprecated alias to nix store add.

Synopsis

nix store add-path [option...] path

Options

  • --dry-run

    Show what this command would do without doing it.

  • --hash-algo hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --mode content-address-method

    How to compute the content-address of the store object. One of:

    • nar (the default): Serialises the input as a Nix Archive and passes that to the hash function.

    • flat: Assumes that the input is a single file and directly passes it to the hash function.

    • text: Like flat, but used for derivations serialized in store object and builtins.toFile. For advanced use-cases only; for regular usage prefer nar and flat.

  • --name / -n name

    Override the name component of the store path. It defaults to the base name of path.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store cat - print the contents of a file in the Nix store on stdout

Synopsis

nix store cat [option...] path

Examples

  • Show the contents of a file in a binary cache:

    # nix store cat --store https://cache.nixos.org/ \
        /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10/bin/hello | hexdump -C | head -n1
    00000000  7f 45 4c 46 02 01 01 00  00 00 00 00 00 00 00 00  |.ELF............|
    

Description

This command prints on standard output the contents of the regular file path in a Nix store. path can be a top-level store path or any file inside a store path.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store copy-log - copy build logs between Nix stores

Synopsis

nix store copy-log [option...] installables...

Examples

  • To copy the build log of the hello package from https://cache.nixos.org to the local store:

    # nix store copy-log --from https://cache.nixos.org --eval-store auto nixpkgs#hello
    

    You can verify that the log is available locally:

    # nix log --substituters '' nixpkgs#hello
    

    (The flag --substituters '' avoids querying https://cache.nixos.org for the log.)

  • To copy the log for a specific store derivation via SSH:

    # nix store copy-log --to ssh-ng://machine /nix/store/ilgm50plpmcgjhcp33z6n4qbnpqfhxym-glibc-2.33-59.drv
    

Description

nix store copy-log copies build logs between two Nix stores. The source store is specified using --from and the destination using --to. If one of these is omitted, it defaults to the local store.

Options

  • --from store-uri

    URL of the source Nix store.

  • --stdin

    Read installables from the standard input. No default installable applied.

  • --to store-uri

    URL of the destination Nix store.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store copy-sigs - copy store path signatures from substituters

Synopsis

nix store copy-sigs [option...] installables...

Options

  • --stdin

    Read installables from the standard input. No default installable applied.

  • --substituter / -s store-uri

    Copy signatures from the specified store.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store delete - delete paths from the Nix store

Synopsis

nix store delete [option...] installables...

Examples

  • Delete a specific store path:

    # nix store delete /nix/store/yb5q57zxv6hgqql42d5r8b5k5mcq6kay-hello-2.10
    

Description

This command deletes the store paths specified by installables, 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, nix store delete is a more targeted version of nix store 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).

Options

  • --ignore-liveness

    Do not check whether the paths are reachable from a root.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store diff-closures - show what packages and versions were added and removed between two closures

Synopsis

nix store diff-closures [option...] before after

Examples

  • Show what got added and removed between two versions of the NixOS system profile:

    # nix store diff-closures /nix/var/nix/profiles/system-655-link /nix/var/nix/profiles/system-658-link
    acpi-call: 2020-04-07-5.8.16 → 2020-04-07-5.8.18
    baloo-widgets: 20.08.1 → 20.08.2
    bluez-qt: +12.6 KiB
    dolphin: 20.08.1 → 20.08.2, +13.9 KiB
    kdeconnect: 20.08.2 → ∅, -6597.8 KiB
    kdeconnect-kde: ∅ → 20.08.2, +6599.7 KiB
    …
    

Description

This command shows the differences between the two closures before and after with respect to the addition, removal, or version change of packages, as well as changes in store path sizes.

For each package name in the two closures (where a package name is defined as the name component of a store path excluding the version), if there is a change in the set of versions of the package, or a change in the size of the store paths of more than 8 KiB, it prints a line like this:

dolphin: 20.08.1 → 20.08.2, +13.9 KiB

No size change is shown if it's below the threshold. If the package does not exist in either the before or after closures, it is represented using (empty set) on the appropriate side of the arrow. If a package has an empty version string, the version is rendered as ε (epsilon).

There may be multiple versions of a package in each closure. In that case, only the changed versions are shown. Thus,

libfoo: 1.2, 1.3 → 1.4

leaves open the possibility that there are other versions (e.g. 1.1) that exist in both closures.

Options

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store dump-path - serialise a store path to stdout in NAR format

Synopsis

nix store dump-path [option...] installables...

Examples

  • To get a NAR containing the GNU Hello package:

    # nix store dump-path nixpkgs#hello > hello.nar
    
  • To get a NAR from the binary cache https://cache.nixos.org/:

    # nix store dump-path --store https://cache.nixos.org/ \
        /nix/store/7crrmih8c52r8fbnqb933dxrsp44md93-glibc-2.25 > glibc.nar
    

Description

This command generates a Nix Archive (NAR) file containing the serialisation of the store path installable. The NAR is written to standard output.

Options

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store gc - perform garbage collection on a Nix store

Synopsis

nix store gc [option...]

Examples

  • Delete unreachable paths in the Nix store:

    # nix store gc
    
  • Delete up to 1 gigabyte of garbage:

    # nix store gc --max 1G
    

Description

This command deletes unreachable paths in the Nix store.

Options

  • --dry-run

    Show what this command would do without doing it.

  • --max n

    Stop after freeing n bytes of disk space.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store info - test whether a store can be accessed

Synopsis

nix store info [option...]

Examples

  • Test whether connecting to a remote Nix store via SSH works:

    # nix store info --store ssh://mac1
    
  • Test whether a URL is a valid binary cache:

    # nix store info --store https://cache.nixos.org
    
  • Test whether the Nix daemon is up and running:

    # nix store info --store daemon
    

Description

This command tests whether a particular Nix store (specified by the argument --store url) can be accessed. What this means is dependent on the type of the store. For instance, for an SSH store it means that Nix can connect to the specified machine.

If the command succeeds, Nix returns a exit code of 0 and does not print any output.

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store ls - show information about a path in the Nix store

Synopsis

nix store ls [option...] path

Examples

  • To list the contents of a store path in a binary cache:

    # nix store ls --store https://cache.nixos.org/ --long --recursive /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10
    dr-xr-xr-x                    0 ./bin
    -r-xr-xr-x                38184 ./bin/hello
    dr-xr-xr-x                    0 ./share
    …
    
  • To show information about a specific file in a binary cache:

    # nix store ls --store https://cache.nixos.org/ --long /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10/bin/hello
    -r-xr-xr-x                38184 hello
    

Description

This command shows information about path in a Nix store. path can be a top-level store path or any file inside a store path.

Options

  • --directory / -d

    Show directories rather than their contents.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --long / -l

    Show detailed file information.

  • --recursive / -R

    List subdirectories recursively.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store make-content-addressed - rewrite a path or closure to content-addressed form

Synopsis

nix store make-content-addressed [option...] installables...

Examples

  • Create a content-addressed representation of the closure of GNU Hello:

    # nix store make-content-addressed nixpkgs#hello
    …
    rewrote '/nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10' to '/nix/store/5skmmcb9svys5lj3kbsrjg7vf2irid63-hello-2.10'
    

    Since the resulting paths are content-addressed, they are always trusted and don't need signatures to copied to another store:

    # nix copy --to /tmp/nix --trusted-public-keys '' /nix/store/5skmmcb9svys5lj3kbsrjg7vf2irid63-hello-2.10
    

    By contrast, the original closure is input-addressed, so it does need signatures to be trusted:

    # nix copy --to /tmp/nix --trusted-public-keys '' nixpkgs#hello
    cannot add path '/nix/store/zy9wbxwcygrwnh8n2w9qbbcr6zk87m26-libunistring-0.9.10' because it lacks a signature by a trusted key
    
  • Create a content-addressed representation of the current NixOS system closure:

    # nix store make-content-addressed /run/current-system
    

Description

This command converts the closure of the store paths specified by installables to content-addressed form.

Nix store paths are usually input-addressed, meaning that the hash part of the store path is computed from the contents of the derivation (i.e., the build-time dependency graph). Input-addressed paths need to be signed by a trusted key if you want to import them into a store, because we need to trust that the contents of the path were actually built by the derivation.

By contrast, in a content-addressed path, the hash part is computed from the contents of the path. This allows the contents of the path to be verified without any additional information such as signatures. This means that a command like

# nix store build /nix/store/5skmmcb9svys5lj3kbsrjg7vf2irid63-hello-2.10 \
    --substituters https://my-cache.example.org

will succeed even if the binary cache https://my-cache.example.org doesn't present any signatures.

Options

  • --from store-uri

    URL of the source Nix store.

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --stdin

    Read installables from the standard input. No default installable applied.

  • --to store-uri

    URL of the destination Nix store.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store optimise - replace identical files in the store by hard links

Synopsis

nix store optimise [option...]

Examples

  • Optimise the Nix store:

    nix store optimise
    

Description

This command deduplicates the Nix store: it scans the store for regular files with identical contents, and replaces them with hard links to a single instance.

Note that you can also set auto-optimise-store to true in nix.conf to perform this optimisation incrementally whenever a new path is added to the Nix store. To make this efficient, Nix maintains a content-addressed index of all the files in the Nix store in the directory /nix/store/.links/.

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store path-from-hash-part - get a store path from its hash part

Synopsis

nix store path-from-hash-part [option...] hash-part

Examples

  • Return the full store path with the given hash part:

    # nix store path-from-hash-part --store https://cache.nixos.org/ 0i2jd68mp5g6h2sa5k9c85rb80sn8hi9
    /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10
    

Description

Given the hash part of a store path (that is, the 32 characters following /nix/store/), return the full store path. This is primarily useful in the implementation of binary caches, where a request for a .narinfo file only supplies the hash part (e.g. https://cache.nixos.org/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9.narinfo).

Options

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store ping - test whether a store can be accessed

Synopsis

nix store ping [option...]

Examples

  • Test whether connecting to a remote Nix store via SSH works:

    # nix store info --store ssh://mac1
    
  • Test whether a URL is a valid binary cache:

    # nix store info --store https://cache.nixos.org
    
  • Test whether the Nix daemon is up and running:

    # nix store info --store daemon
    

Description

This command tests whether a particular Nix store (specified by the argument --store url) can be accessed. What this means is dependent on the type of the store. For instance, for an SSH store it means that Nix can connect to the specified machine.

If the command succeeds, Nix returns a exit code of 0 and does not print any output.

Options

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store prefetch-file - download a file into the Nix store

Synopsis

nix store prefetch-file [option...] url

Examples

  • Download a file to the Nix store:

    # nix store prefetch-file https://releases.nixos.org/nix/nix-2.3.10/nix-2.3.10.tar.xz
    Downloaded 'https://releases.nixos.org/nix/nix-2.3.10/nix-2.3.10.tar.xz' to
    '/nix/store/vbdbi42hgnc4h7pyqzp6h2yf77kw93aw-source' (hash
    'sha256-qKheVd5D0BervxMDbt+1hnTKE2aRWC8XCAwc0SeHt6s=').
    
  • Download a file and get the SHA-512 hash:

    # nix store prefetch-file --json --hash-type sha512 \
        https://releases.nixos.org/nix/nix-2.3.10/nix-2.3.10.tar.xz \
      | jq -r .hash
    sha512-6XJxfym0TNH9knxeH4ZOvns6wElFy3uahunl2hJgovACCMEMXSy42s69zWVyGJALXTI+86tpDJGlIcAySEKBbA==
    

Description

This command downloads the file url to the Nix store. It prints out the resulting store path and the cryptographic hash of the contents of the file.

The name component of the store path defaults to the last component of url, but this can be overridden using --name.

Options

  • --executable

    Make the resulting file executable. Note that this causes the resulting hash to be a NAR hash rather than a flat file hash.

  • --expected-hash hash

    The expected hash of the file.

  • --hash-type hash-algo

    Hash algorithm (blake3, md5, sha1, sha256, or sha512).

  • --json

    Produce output in JSON format, suitable for consumption by another program.

  • --name name

    Override the name component of the resulting store path. It defaults to the base name of url.

  • --unpack

    Unpack the archive (which must be a tarball or zip file) and add the result to the Nix store.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store repair - repair store paths

Synopsis

nix store repair [option...] installables...

Examples

  • Repair a store path, after determining that it is corrupt:

    # nix store verify /nix/store/yb5q57zxv6hgqql42d5r8b5k5mcq6kay-hello-2.10
    path '/nix/store/yb5q57zxv6hgqql42d5r8b5k5mcq6kay-hello-2.10' was
    modified! expected hash
    'sha256:1hd5vnh6xjk388gdk841vflicy8qv7qzj2hb7xlyh8lpb43j921l', got
    'sha256:1a25lf78x5wi6pfkrxalf0n13kdaca0bqmjqnp7wfjza2qz5ssgl'
    
    # nix store repair /nix/store/yb5q57zxv6hgqql42d5r8b5k5mcq6kay-hello-2.10
    

Description

This command attempts to "repair" the store paths specified by installables 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).

Options

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store sign - sign store paths with a local key

Synopsis

nix store sign [option...] installables...

Options

  • --key-file / -k file

    File containing the secret signing key.

  • --stdin

    Read installables from the standard input. No default installable applied.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix store verify - verify the integrity of store paths

Synopsis

nix store verify [option...] installables...

Examples

  • Verify the entire Nix store:

    # nix store verify --all
    
  • Check whether each path in the closure of Firefox has at least 2 signatures:

    # nix store verify --recursive --sigs-needed 2 --no-contents $(type -p firefox)
    
  • Verify a store path in the binary cache https://cache.nixos.org/:

    # nix store verify --store https://cache.nixos.org/ \
        /nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10
    

Description

This command verifies the integrity of the store paths installables, or, if --all is given, the entire Nix store. For each path, it checks that

  • its contents match the NAR hash recorded in the Nix database; and

  • it is trusted, that is, it is signed by at least one trusted signing key, is content-addressed, or is built locally ("ultimately trusted").

Exit status

The exit status of this command is the sum of the following values:

  • 1 if any path is corrupted (i.e. its contents don't match the recorded NAR hash).

  • 2 if any path is untrusted.

  • 4 if any path couldn't be verified for any other reason (such as an I/O error).

Options

  • --no-contents

    Do not verify the contents of each store path.

  • --no-trust

    Do not verify whether each store path is trusted.

  • --sigs-needed / -n n

    Require that each path is signed by at least n different keys.

  • --stdin

    Read installables from the standard input. No default installable applied.

  • --substituter / -s store-uri

    Use signatures from the specified store.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --all

    Apply the operation to every store path.

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

  • --recursive / -r

    Apply operation to closure of the specified paths.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix upgrade-nix - upgrade Nix to the latest stable version

Synopsis

nix upgrade-nix [option...]

Examples

  • Upgrade Nix to the stable version declared in Nixpkgs:

    # nix upgrade-nix
    
  • Upgrade Nix in a specific profile:

    # nix upgrade-nix --profile ~alice/.local/state/nix/profiles/profile
    

Description

This command upgrades Nix to the stable version.

By default, the latest stable version is defined by Nixpkgs, in nix-fallback-paths.nix and updated manually. It may not always be the latest tagged release.

By default, it locates the directory containing the nix binary in the $PATH environment variable. If that directory is a Nix profile, it will upgrade the nix package in that profile to the latest stable binary release.

You cannot use this command to upgrade Nix in the system profile of a NixOS system (that is, if nix is found in /run/current-system).

Options

  • --dry-run

    Show what this command would do without doing it.

  • --nix-store-paths-url url

    The URL of the file that contains the store paths of the latest Nix release.

  • --profile / -p profile-dir

    The path to the Nix profile to upgrade.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --version

    Show version information.

Note

See man nix.conf for overriding configuration settings with command line flags.

Name

nix why-depends - show why a package has another package in its closure

Synopsis

nix why-depends [option...] package dependency

Examples

  • Show one path through the dependency graph leading from Hello to Glibc:

    # nix why-depends nixpkgs#hello nixpkgs#glibc
    /nix/store/v5sv61sszx301i0x6xysaqzla09nksnd-hello-2.10
    └───bin/hello: …...................../nix/store/9l06v7fc38c1x3r2iydl15ksgz0ysb82-glibc-2.32/lib/ld-linux-x86-64.…
        → /nix/store/9l06v7fc38c1x3r2iydl15ksgz0ysb82-glibc-2.32
    
  • Show all files and paths in the dependency graph leading from Thunderbird to libX11:

    # nix why-depends --all nixpkgs#thunderbird nixpkgs#xorg.libX11
    /nix/store/qfc8729nzpdln1h0hvi1ziclsl3m84sr-thunderbird-78.5.1
    ├───lib/thunderbird/libxul.so: …6wrw-libxcb-1.14/lib:/nix/store/adzfjjh8w25vdr0xdx9x16ah4f5rqrw5-libX11-1.7.0/lib:/nix/store/ssf…
    │   → /nix/store/adzfjjh8w25vdr0xdx9x16ah4f5rqrw5-libX11-1.7.0
    ├───lib/thunderbird/libxul.so: …pxyc-libXt-1.2.0/lib:/nix/store/1qj29ipxl2fyi2b13l39hdircq17gnk0-libXdamage-1.1.5/lib:/nix/store…
    │   → /nix/store/1qj29ipxl2fyi2b13l39hdircq17gnk0-libXdamage-1.1.5
    │   ├───lib/libXdamage.so.1.1.0: …-libXfixes-5.0.3/lib:/nix/store/adzfjjh8w25vdr0xdx9x16ah4f5rqrw5-libX11-1.7.0/lib:/nix/store/9l0…
    │   │   → /nix/store/adzfjjh8w25vdr0xdx9x16ah4f5rqrw5-libX11-1.7.0
    …
    
  • Show why Glibc depends on itself:

    # nix why-depends nixpkgs#glibc nixpkgs#glibc
    /nix/store/9df65igwjmf2wbw0gbrrgair6piqjgmi-glibc-2.31
    └───lib/ld-2.31.so: …che       Do not use /nix/store/9df65igwjmf2wbw0gbrrgair6piqjgmi-glibc-2.31/etc/ld.so.cache.  --…
        → /nix/store/9df65igwjmf2wbw0gbrrgair6piqjgmi-glibc-2.31
    
  • Show why Geeqie has a build-time dependency on systemd:

    # nix why-depends --derivation nixpkgs#geeqie nixpkgs#systemd
    /nix/store/drrpq2fqlrbj98bmazrnww7hm1in3wgj-geeqie-1.4.drv
    └───/: …atch.drv",["out"]),("/nix/store/qzh8dyq3lfbk3i1acbp7x9wh3il2imiv-gtk+3-3.24.21.drv",["dev"]),("/…
        → /nix/store/qzh8dyq3lfbk3i1acbp7x9wh3il2imiv-gtk+3-3.24.21.drv
        └───/: …16.0.drv",["dev"]),("/nix/store/8kp79fyslf3z4m3dpvlh6w46iaadz5c2-cups-2.3.3.drv",["dev"]),("/nix…
            → /nix/store/8kp79fyslf3z4m3dpvlh6w46iaadz5c2-cups-2.3.3.drv
            └───/: ….3.1.drv",["out"]),("/nix/store/yd3ihapyi5wbz1kjacq9dbkaq5v5hqjg-systemd-246.4.drv",["dev"]),("/…
                → /nix/store/yd3ihapyi5wbz1kjacq9dbkaq5v5hqjg-systemd-246.4.drv
    

Description

Nix automatically determines potential runtime dependencies between store paths by scanning for the hash parts of store paths. For instance, if there exists a store path /nix/store/9df65igwjmf2wbw0gbrrgair6piqjgmi-glibc-2.31, and a file inside another store path contains the string 9df65igw…, then the latter store path refers to the former, and thus might need it at runtime. Nix always maintains the existence of the transitive closure of a store path under the references relationship; it is therefore not possible to install a store path without having all of its references present.

Sometimes Nix packages end up with unexpected runtime dependencies; for instance, a reference to a compiler might accidentally end up in a binary, causing the former to be in the latter's closure. This kind of closure size bloat is undesirable.

nix why-depends allows you to diagnose the cause of such issues. It shows why the store path package depends on the store path dependency, by showing a shortest sequence in the references graph from the former to the latter. Also, for each node along this path, it shows a file fragment containing a reference to the next store path in the sequence.

To show why derivation package has a build-time rather than runtime dependency on derivation dependency, use --derivation.

Options

  • --all / -a

    Show all edges in the dependency graph leading from package to dependency, rather than just a shortest path.

  • --precise

    For each edge in the dependency graph, show the files in the parent that cause the dependency.

Common evaluation options

  • --arg name expr

    Pass the value expr as the argument name to Nix functions.

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --argstr name string

    Pass the string string as the argument name to Nix functions.

  • --debugger

    Start an interactive environment if evaluation fails.

  • --eval-store store-url

    The URL of the Nix store to use for evaluation, i.e. to store derivations (.drv files) and inputs referenced by them.

  • --impure

    Allow access to mutable paths and repositories.

  • --include / -I path

    Add path to search path entries used to resolve lookup paths

    This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --override-flake original-ref resolved-ref

    Override the flake registries, redirecting original-ref to resolved-ref.

  • --debug

    Set the logging verbosity level to 'debug'.

  • --log-format format

    Set the format of log output; one of raw, internal-json, bar or bar-with-logs.

  • --print-build-logs / -L

    Print full build logs on standard error.

  • --quiet

    Decrease the logging verbosity level.

  • --verbose / -v

    Increase the logging verbosity level.

Miscellaneous global options

  • --help

    Show usage information.

  • --offline

    Disable substituters and consider all previously downloaded files up-to-date.

  • --option name value

    Set the Nix configuration setting name to value (overriding nix.conf).

  • --refresh

    Consider all previously downloaded files out-of-date.

  • --repair

    During evaluation, rewrite missing or corrupted files in the Nix store. During building, rebuild missing or corrupted store paths.

  • --version

    Show version information.

Options that change the interpretation of installables

  • --derivation

    Operate on the store derivation rather than its outputs.

  • --expr expr

    Interpret installables as attribute paths relative to the Nix expression expr.

  • --file / -f file

    Interpret installables as attribute paths relative to the Nix expression stored in file. If file is the character -, then a Nix expression will be read from standard input. Implies --impure.

Note

See man nix.conf for overriding configuration settings with command line flags.

Main Commands

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

Name

nix-build - build a Nix expression

Synopsis

nix-build [paths…] [--arg name value] [--argstr name value] [{--attr | -A} attrPath] [--no-out-link] [--dry-run] [{--out-link | -o} outlink]

Disambiguation

This man page describes the command nix-build, which is distinct from nix build. For documentation on the latter, run nix build --help or see man nix3-build.

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 (result, result-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.

  • --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.

  • --dry-run

    Show what store paths would be built or downloaded.

  • --out-link / -o outlink

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

Special exit codes for build failure

1xx status codes are used when requested builds failed. The following codes are in use:

  • 100 Generic build failure

    The builder process returned with a non-zero exit code.

  • 101 Build timeout

    The build was aborted because it did not complete within the specified timeout.

  • 102 Hash mismatch

    The build output was rejected because it does not match the outputHash attribute of the derivation.

  • 104 Not deterministic

    The build succeeded in check mode but the resulting output is not binary reproducible.

With the --keep-going flag it's possible for multiple failures to occur. In this case the 1xx status codes are or combined using bitwise OR.

0b1100100
     ^^^^
     |||`- timeout
     ||`-- output hash mismatch
     |`--- build failure
     `---- not deterministic

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

$ nix-build '<nixpkgs>' --attr 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>' --attr 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 out, bin and man, nix-build will create symlinks result, result-bin and result-man. It’s also possible to build a specific output:

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

This will create a symlink result-man.

Build a Nix expression given on the command line:

$ nix-build --expr '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 --attr hello

Name

nix-channel - manage Nix channels

Synopsis

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

Description

Channels are a mechanism for referencing remote Nix expressions and conveniently retrieving their latest version.

The moving parts of channels are:

Note

The state of a subscribed channel is external to the Nix expressions relying on it. This may limit reproducibility.

Dependencies on other Nix expressions can be declared explicitly with:

This command has the following operations:

  • --add url [name]

    Add a channel name located at url to the list of subscribed channels. If name is omitted, default to the last component of url, with the suffixes -stable or -unstable removed.

    Note

    --add does not automatically perform an update. Use --update explicitly.

    A channel URL must point to a directory containing a file nixexprs.tar.gz. At the top level, that tarball must contain a single directory with a default.nix file that serves as the channel’s entry point.

  • --remove name

    Remove the channel name from the list of subscribed channels.

  • --list

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

  • --update [names…]

    Download the Nix expressions of subscribed channels and create a new generation. Update all channels if none is specified, and only those included in names otherwise.

  • --list-generations

    Prints a list of all the current existing generations for the channel profile.

    Works the same way as

    nix-env --profile /nix/var/nix/profiles/per-user/$USER/channels --list-generations
    
  • --rollback [generation]

    Revert channels to the state before the last call to nix-channel --update. Optionally, you can specify a specific channel generation number to restore.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Files

nix-channel operates on the following files.

Channels

A directory containing symlinks to Nix channels, managed by nix-channel:

  • $XDG_STATE_HOME/nix/profiles/channels for regular users
  • $NIX_STATE_DIR/profiles/per-user/root/channels for root

nix-channel uses a profile to store channels. This profile contains symlinks to the contents of those channels.

Subscribed channels

The list of subscribed channels is stored in

in the following format:

<url> <name>
...

Examples

Subscribe to the Nixpkgs channel and run hello from the GNU Hello package:

$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --list
nixpkgs https://nixos.org/channels/nixpkgs
$ nix-channel --update
$ nix-shell -p hello --run hello
hello

Revert channel updates using --rollback:

$ nix-instantiate --eval '<nixpkgs>' --attr lib.version
"22.11pre296212.530a53dcbc9"

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

$ nix-instantiate --eval '<nixpkgs>' --attr lib.version
"22.11pre281526.d0419badfad"

Remove a channel:

$ nix-channel --remove nixpkgs
$ nix-channel --list

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 | expressions} … | [path]}

Disambiguation

This man page describes the command nix-shell, which is distinct from nix shell. For documentation on the latter, run nix shell --help or see man nix3-shell.

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 run 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"
    export SOME_API_TOKEN="$(cat ~/.config/some-app/api-token)"
  '';

will cause nix-shell to print Hello shell and set the SOME_API_TOKEN environment variable to a user-configured value.

Options

All options not listed here are passed to nix-store --realise, except for --arg and --attr / -A which are passed to nix-instantiate.

  • --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 to exit 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 Hello and 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 HOME, USER and DISPLAY, are retained. Note that the shell used to run commands is obtained from NIX_BUILD_SHELL / <nixpkgs> from NIX_PATH, and therefore not affected by --pure.

  • --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 --packages 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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_BUILD_SHELL

    Shell used to start the interactive environment. Defaults to the bash from bashInteractive found in <nixpkgs>, falling back to the bash found in PATH if not found.

    Note

    The shell obtained using this method may not necessarily be the same as any shells requested in path.

    **Example

    Despite --pure, this invocation will not result in a fully reproducible shell environment:

    #!/usr/bin/env -S nix-shell --pure
    let
      pkgs = import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/854fdc68881791812eddd33b2fed94b954979a8e.tar.gz") {};
    in
    pkgs.mkShell {
      buildInputs = pkgs.bashInteractive;
    }
    

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

$ nix-shell '<nixpkgs>' --attr pan
[nix-shell]$ eval ${unpackPhase:-unpackPhase}
[nix-shell]$ cd $sourceRoot
[nix-shell]$ eval ${patchPhase:-patchPhase}
[nix-shell]$ eval ${configurePhase:-configurePhase}
[nix-shell]$ eval ${buildPhase:-buildPhase}
[nix-shell]$ ./pan/gui/pan

The reason we use form eval ${configurePhase:-configurePhase} here is because those packages that override these phases do so by exporting the overridden values in the environment variable of the same name. Here bash is being told to either evaluate the contents of 'configurePhase', if it exists as a variable, otherwise evaluate the configurePhase function.

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

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

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

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

A shorter way to do the same is:

$ nix-shell --packages 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 …

Note that -p accepts multiple full nix expressions that are valid in the buildInputs = [ ... ] shown above, not only package names. So the following is also legal:

$ nix-shell --packages sqlite 'git.override { withManual = false; }'

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 --packages pan -I nixpkgs=https://github.com/NixOS/nixpkgs/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 --packages 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 python3 --packages python3 python3Packages.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 --packages 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 --packages 'terraform.withPlugins (plugins: [ plugins.openstack ])'

terraform apply

Note

You must use single or 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 20.03 stable branch):

#! /usr/bin/env nix-shell
#! nix-shell -i runghc --packages 'haskellPackages.ghcWithPackages (ps: [ps.download-curl ps.tagsoup])'
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-20.03.tar.gz

import Network.Curl.Download
import Text.HTML.TagSoup
import Data.Either
import Data.ByteString.Char8 (unpack)

-- Fetch nixos.org and print all hrefs.
main = do
  resp <- openURI "https://nixos.org/"
  let tags = filter (isTagOpenName "a") $ parseTags $ unpack $ fromRight undefined resp
  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/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 ]; } ""

The script's file name is passed as the first argument to the interpreter specified by the -i flag.

Aside from the very first line, which is a directive to the operating system, the additional #! nix-shell lines do not need to be at the beginning of the file. This allows wrapping them in block comments for languages where # does not start a comment, such as ECMAScript, Erlang, PHP, or Ruby.

Name

nix-store - manipulate or query the Nix store

Synopsis

nix-store operation [options…] [arguments…] [--option name value] [--add-root path]

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. The following operations are available:

These pages can be viewed offline:

  • man nix-store-<operation>.

    Example: man nix-store-realise

  • nix-store --help --<operation>

    Example: nix-store --help --realise

Name

nix-store --add-fixed - add paths to store using given hashing algorithm

Synopsis

nix-store --add-fixed [--recursive] algorithm paths…

Description

The operation --add-fixed adds the specified paths to the Nix store. Unlike --add paths are registered using the specified hashing algorithm, resulting in the same output path as a fixed-output derivation. This can be used for sources that are not available from a public url or broke since the download expression was written.

This operation has the following options:

  • --recursive

    Use recursive instead of flat hashing mode, used when adding directories to the store.

    paths that refer to symlinks are not dereferenced, but added to the store as symlinks with the same target.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Example

$ nix-store --add-fixed sha256 ./hello-2.10.tar.gz
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz

Name

nix-store --add - add paths to Nix store

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.

paths that refer to symlinks are not dereferenced, but added to the store as symlinks with the same target.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Example

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

Name

nix-store --delete - delete store paths

Synopsis

nix-store --delete [--ignore-liveness] paths…

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).

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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

Name

nix-store --dump-db - export Nix database

Synopsis

nix-store --dump-db [paths…]

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.

By default, --dump-db will dump the entire Nix database. When one or more store paths is passed, only the subset of the Nix database for those store paths is dumped. As with --export, the user is responsible for passing all the store paths for a closure. See --export for an example.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Name

nix-store --dump - write a single path to a Nix Archive

Synopsis

nix-store --dump path

Description

The operation --dump produces a Nix archive (NAR) 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 444 or 555 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 --query --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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Name

nix-store --export - export store paths to a Nix Archive

Synopsis

nix-store --export paths…

Description

The operation --export writes a serialisation of the given store objects to standard output in a format that can be imported into another Nix store with nix-store --import.

Warning

This command does not produce a closure of the specified store paths. Trying to import a store object that refers to store paths not available in the target Nix store will fail.

Use nix-store --query to obtain the closure of a store path.

This command is different from nix-store --dump, which produces a Nix archive that does not contain the set of references of a given store path.

Note

For efficient transfer of closures to remote machines over SSH, use nix-copy-closure.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

Example

Deploy GNU Hello to an airgapped machine via USB stick.

Write the closure to the block device on a machine with internet connection:

[alice@itchy]$ storePath=$(nix-build '<nixpkgs>' -I nixpkgs=channel:nixpkgs-unstable -A hello --no-out-link)
[alice@itchy]$ nix-store --export $(nix-store --query --requisites $storePath) | sudo dd of=/dev/usb

Read the closure from the block device on the machine without internet connection:

[bob@scratchy]$ hello=$(sudo dd if=/dev/usb | nix-store --import | tail -1)
[bob@scratchy]$ $hello/bin/hello
Hello, world!

Name

nix-store --gc - run garbage collection

Synopsis

nix-store --gc [--print-roots | --print-live | --print-dead] [--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.

  • --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.

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 K, M, G or T, denoting KiB, MiB, GiB or TiB units.

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

By default, 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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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))

Name

nix-store --generate-binary-cache-key - generate key pair to use for a binary cache

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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Name

nix-store --import - import Nix Archive into the store

Synopsis

nix-store --import

Description

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

Note

For efficient transfer of closures to remote machines over SSH, use nix-copy-closure.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

Example

Given a closure of GNU Hello as a file:

$ storePath="$(nix-build '<nixpkgs>' -I nixpkgs=channel:nixpkgs-unstable -A hello --no-out-link)"
$ nix-store --export $(nix-store --query --requisites $storePath) > hello.closure

Import the closure into a remote SSH store using the --store option:

$ nix-store --import --store ssh://alice@itchy.example.org < hello.closure

Name

nix-store --load-db - import Nix database

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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Name

nix-store --optimise - reduce disk space usage

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 Nix Archive (NAR) 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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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

Name

nix-store --print-env - print the build environment of a derivation

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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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'

Name

nix-store --query - display information about store paths

Synopsis

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

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 existing output paths 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 that was used to build 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 string unknown-deriver is printed. The returned deriver is not guaranteed to exist in the local store, for example when paths were substituted from a binary cache. Use --valid-derivers instead to obtain valid paths only.

  • --valid-derivers

    Prints a set of derivation files (.drv) which are supposed produce said paths when realized. Might print nothing, for example for source paths or paths substituted from a binary cache.

  • --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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

$ nix-store --query --requisites $(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 --query --requisites $(nix-store --query --deriver $(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 --query --tree $(nix-store --query --deriver $(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 --query --referrers $(nix-store --query --binding openssl $(nix-store --query --deriver $(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 --query --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 --query --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 --query --roots $(which svn)
/nix/var/nix/profiles/default-81-link
/nix/var/nix/profiles/default-82-link
/home/eelco/.local/state/nix/profiles/profile-97-link

Name

nix-store --read-log - print build 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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Example

$ nix-store --read-log $(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
...

Name

nix-store --realise - build or fetch store objects

Synopsis

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

Description

Each of paths is processed as follows:

If no substitutes are available and no store derivation is given, realisation fails.

The resulting paths are printed on standard output. For non-derivation arguments, the argument itself is printed.

Special exit codes for build failure

1xx status codes are used when requested builds failed. The following codes are in use:

  • 100 Generic build failure

    The builder process returned with a non-zero exit code.

  • 101 Build timeout

    The build was aborted because it did not complete within the specified timeout.

  • 102 Hash mismatch

    The build output was rejected because it does not match the outputHash attribute of the derivation.

  • 104 Not deterministic

    The build succeeded in check mode but the resulting output is not binary reproducible.

With the --keep-going flag it's possible for multiple failures to occur. In this case the 1xx status codes are or combined using bitwise OR.

0b1100100
     ^^^^
     |||`- timeout
     ||`-- output hash mismatch
     |`--- build failure
     `---- not deterministic

Options

  • --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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

$ nix-store --realise $(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>' --attr hello --check -K

Use nix-store --read-log to show the stderr and stdout of a build:

$ nix-store --read-log $(nix-instantiate ./test.nix)

Name

nix --repair-path - re-download path from substituter

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'...
…

Name

nix-store --restore - extract a Nix archive

Synopsis

nix-store --restore path

Description

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

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Name

nix-store --serve - serve local Nix store over SSH

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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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

Name

nix-store --verify-path - check path contents against Nix database

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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Example

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

$ nix-store --verify-path $(nix-store --query --requisites $(which svn))

Name

nix-store --verify - check Nix database for consistency

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.

Options

The following options are allowed for all nix-store operations, but may not always have an effect.

  • --add-root path

    Causes the result of a realisation (--realise and --force-realise) to be registered as a root of the garbage collector. path will be created as a symlink to the resulting store path. In addition, a uniquely named symlink to path will be created in /nix/var/nix/gcroots/auto/. For instance,

    $ nix-store --add-root /home/eelco/bla/result --realise ...
    
    $ 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 GC roots, since the symlink in the auto directory will still point to the old location.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Name

nix-env - manipulate or query Nix user environments

Synopsis

nix-env operation [options] [arguments…] [--option name value] [--arg name value] [--argstr name value] [{--file | -f} path] [{--profile | -p} path] [--system-filter system] [--dry-run]

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. The following operations are available:

These pages can be viewed offline:

  • man nix-env-<operation>.

    Example: man nix-env-install

  • nix-env --help --<operation>

    Example: nix-env --help --install

Package sources

nix-env can obtain packages from multiple sources:

  • An attribute set of derivations from:
    • The default Nix expression (by default)
    • A Nix file, specified via --file
    • A profile, specified via --from-profile
    • A Nix expression that is a function which takes default expression as argument, specified via --from-expression
  • A store path

Selectors

Several operations, such as nix-env --query and nix-env --install, take a list of arguments that specify the packages on which to operate.

Packages are identified based on a name part and a version part of a symbolic derivation name:

  • name: Everything up to but not including the first dash (-) that is not followed by a letter.
  • version: The rest, excluding the separating dash.

Example

nix-env parses the symbolic derivation name apache-httpd-2.0.48 as:

{
  "name": "apache-httpd",
  "version": "2.0.48"
}

Example

nix-env parses the symbolic derivation name firefox.* as:

{
  "name": "firefox.*",
  "version": ""
}

The name parts of the arguments to nix-env are treated as extended regular expressions and matched against the name parts of derivation names in the package source. 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. For details on regular expressions, see regex(7).

Example

Common patterns for finding package names with nix-env:

  • 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.

Files

nix-env operates on the following files.

Default Nix expression

The source for the Nix expressions used by nix-env by default:

It is loaded as follows:

  • If the default expression is a file, it is loaded as a Nix expression.
  • If the default expression is a directory containing a default.nix file, that default.nix file is loaded as a Nix expression.
  • If the default expression is a directory without a default.nix file, then its contents (both files and subdirectories) are loaded as Nix expressions. The expressions are combined into a single attribute set, each expression under an attribute with the same name as the original file or subdirectory. Subdirectories without a default.nix file are traversed recursively in search of more Nix expressions, but the names of these intermediate directories are not added to the attribute paths of the default Nix expression.

Then, the resulting expression is interpreted like this:

  • If the expression is an attribute set, it is used as the default Nix expression.
  • If the expression is a function, an empty set is passed as argument and the return value is used as the default Nix expression.

Example

If the default expression contains two files, foo.nix and bar.nix, then the default Nix expression will be equivalent to

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

The file manifest.nix is always ignored.

The command nix-channel places a symlink to the current user's channels in this directory, the user channel link. This makes all subscribed channels available as attributes in the default expression.

A symlink that ensures that nix-env can find the current user's channels:

This symlink points to:

  • $XDG_STATE_HOME/profiles/channels for regular users
  • $NIX_STATE_DIR/profiles/per-user/root/channels for root

In a multi-user installation, you may also have ~/.nix-defexpr/channels_root, which links to the channels of the root user.

Profiles

A directory that contains links to profiles managed by nix-env and nix profile:

  • $XDG_STATE_HOME/nix/profiles for regular users
  • $NIX_STATE_DIR/profiles/per-user/root if the user is root

A profile is a directory of symlinks to files in the Nix store.

Filesystem layout

Profiles are versioned as follows. When using a profile named path, path is a symlink to path-N-link, where N is the version of the profile. In turn, path-N-link is a symlink to a path in the Nix store. For example:

$ ls -l ~alice/.local/state/nix/profiles/profile*
lrwxrwxrwx 1 alice users 14 Nov 25 14:35 /home/alice/.local/state/nix/profiles/profile -> profile-7-link
lrwxrwxrwx 1 alice users 51 Oct 28 16:18 /home/alice/.local/state/nix/profiles/profile-5-link -> /nix/store/q69xad13ghpf7ir87h0b2gd28lafjj1j-profile
lrwxrwxrwx 1 alice users 51 Oct 29 13:20 /home/alice/.local/state/nix/profiles/profile-6-link -> /nix/store/6bvhpysd7vwz7k3b0pndn7ifi5xr32dg-profile
lrwxrwxrwx 1 alice users 51 Nov 25 14:35 /home/alice/.local/state/nix/profiles/profile-7-link -> /nix/store/mp0x6xnsg0b8qhswy6riqvimai4gm677-profile

Each of these symlinks is a root for the Nix garbage collector.

The contents of the store path corresponding to each version of the profile is a tree of symlinks to the files of the installed packages, e.g.

$ ll -R ~eelco/.local/state/nix/profiles/profile-7-link/
/home/eelco/.local/state/nix/profiles/profile-7-link/:
total 20
dr-xr-xr-x 2 root root 4096 Jan  1  1970 bin
-r--r--r-- 2 root root 1402 Jan  1  1970 manifest.nix
dr-xr-xr-x 4 root root 4096 Jan  1  1970 share

/home/eelco/.local/state/nix/profiles/profile-7-link/bin:
total 20
lrwxrwxrwx 5 root root 79 Jan  1  1970 chromium -> /nix/store/ijm5k0zqisvkdwjkc77mb9qzb35xfi4m-chromium-86.0.4240.111/bin/chromium
lrwxrwxrwx 7 root root 87 Jan  1  1970 spotify -> /nix/store/w9182874m1bl56smps3m5zjj36jhp3rn-spotify-1.1.26.501.gbe11e53b-15/bin/spotify
lrwxrwxrwx 3 root root 79 Jan  1  1970 zoom-us -> /nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927/bin/zoom-us

/home/eelco/.local/state/nix/profiles/profile-7-link/share/applications:
total 12
lrwxrwxrwx 4 root root 120 Jan  1  1970 chromium-browser.desktop -> /nix/store/4cf803y4vzfm3gyk3vzhzb2327v0kl8a-chromium-unwrapped-86.0.4240.111/share/applications/chromium-browser.desktop
lrwxrwxrwx 7 root root 110 Jan  1  1970 spotify.desktop -> /nix/store/w9182874m1bl56smps3m5zjj36jhp3rn-spotify-1.1.26.501.gbe11e53b-15/share/applications/spotify.desktop
lrwxrwxrwx 3 root root 107 Jan  1  1970 us.zoom.Zoom.desktop -> /nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927/share/applications/us.zoom.Zoom.desktop

…

Each profile version contains a manifest file:

A symbolic link to the user's current profile:

By default, this symlink points to:

  • $XDG_STATE_HOME/nix/profiles/profile for regular users
  • $NIX_STATE_DIR/profiles/per-user/root/profile for root

The PATH environment variable should include /bin subdirectory of the profile link (e.g. ~/.nix-profile/bin) for the user environment to be visible to the user. The installer sets this up by default, unless you enable use-xdg-base-directories.

Name

nix-env --delete-generations - delete profile generations

Synopsis

nix-env --delete-generations generations

Description

This operation deletes the specified generations of the current profile.

generations can be a one of the following:

  • <number>...

    A list of generation numbers, each one a separate command-line argument.

    Delete exactly the profile generations given by their generation number. Deleting the current generation is not allowed.

  • The special value old

    Delete all generations except the current one.

    WARNING

    Older and newer generations will be deleted by this operation.

    One might expect this to just delete older generations than the curent one, but that is only true if the current generation is also the latest. Because one can roll back to a previous generation, it is possible to have generations newer than the current one. They will also be deleted.

  • <number>d

    The last number days

    Example: 30d

    Delete all generations created more than number days ago, except the most recent one of them. This allows rolling back to generations that were available within the specified period.

  • +<number>

    The last number generations up to the present

    Example: +5

    Keep the last number generations, along with any newer than current.

Periodically deleting old generations is important to make garbage collection effective. The is because profiles are also garbage collection roots — any store object reachable from a profile is "alive" and ineligible for deletion.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

Delete explicit generation numbers

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

Delete the generations numbered 3, 4, and 8, so long as the current active generation is not any of those.

Keep most-recent by count (number of generations)

$ nix-env --delete-generations +5

Suppose 30 is the current generation, and we currently have generations numbered 20 through 32.

Then this command will delete generations 20 through 25 (<= 30 - 5), and keep generations 26 through 31 (> 30 - 5).

Keep most-recent by time (number of days)

$ nix-env --delete-generations 30d

This command will delete all generations older than 30 days, except for the generation that was active 30 days ago (if it currently exists).

Delete all older

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

Name

nix-env --install - add packages to user environment

Synopsis

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

Description

The --install operation creates a new user environment. It is based on the current generation of the active profile, to which a set of store paths described by args is added.

The arguments args map to store paths in a number of possible ways:

  • By default, args is a set of names denoting derivations in the default 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 5.

    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 --install 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 default Nix expression. This is faster than using derivation names and unambiguous. Show the attribute paths of available packages with nix-env --query:

    nix-env --query --available --attr-path
    
  • 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 language functions that are called with the default 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 --priority priority is given, the priority of the derivations being installed is set to priority. This can be used to override the priority of the derivations being installed. This is useful if args are store paths, which don't have any priority information.

  • If args are store paths that point to store derivations, then those store derivations are realised, and the resulting output paths are installed.

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

  • By default all outputs are installed for each store derivation. This can be overridden by adding a meta.outputsToInstall attribute on the derivation listing a subset of the output names.

    Example:

    The file example.nix defines a derivation with two outputs foo and bar, each containing a file.

    # example.nix
    let
      pkgs = import <nixpkgs> {};
      command = ''
        ${pkgs.coreutils}/bin/mkdir -p $foo $bar
        echo foo > $foo/foo-file
        echo bar > $bar/bar-file
      '';
    in
    derivation {
      name = "example";
      builder = "${pkgs.bash}/bin/bash";
      args = [ "-c" command ];
      outputs = [ "foo" "bar" ];
      system = builtins.currentSystem;
    }
    

    Installing from this Nix expression will make files from both outputs appear in the current profile.

    $ nix-env --install --file example.nix
    installing 'example'
    $ ls ~/.nix-profile
    foo-file
    bar-file
    manifest.nix
    

    Adding meta.outputsToInstall to that derivation will make nix-env only install files from the specified outputs.

    # example-outputs.nix
    import ./example.nix // { meta.outputsToInstall = [ "bar" ]; }
    
    $ nix-env --install --file example-outputs.nix
    installing 'example'
    $ ls ~/.nix-profile
    bar-file
    manifest.nix
    

Options

  • --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 clashes 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 --uninstall '.*' first, except that everything happens in a single transaction.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

To install a package using a specific attribute path from the active Nix expression:

$ nix-env --install --attr gcc40mips
installing `gcc-4.0.2'
$ nix-env --install --attr xorg.xorgserver
installing `xorg-server-1.2.0'

To install a specific version of gcc using the derivation name:

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

Using attribute path for selecting a package is preferred, as it is much faster and there will not be multiple matches.

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 all derivations in the Nix expression foo.nix:

$ nix-env --file ~/foo.nix --install '.*'

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

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

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

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

To install a specific output path:

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

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

$ nix-env --file ./foo.nix --install --expr \
    '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 --file '<nixpkgs>' --install --attr hello --dry-run
(dry run; not doing anything)
installing ‘hello-2.10’
this path 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 --file https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz --install --attr firefox

Name

nix-env --list-generations - list profile 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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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)

Name

nix-env --query - display information about packages

Synopsis

nix-env {--query | -q} names… [--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]

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. This option only works together with --available

  • --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 store path to 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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

To show installed packages:

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

To show available packages:

$ nix-env --query --available
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 --query --available --status
-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 --file ./foo.nix --query --available
foo-1.2.3

To compare installed versions to what’s available:

$ nix-env --query --compare-versions
...
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 --query --available '.*zip.*'
bzip2-1.0.6
gzip-1.6
zip-3.0
…

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

$ nix-env --query --available '.*(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 --file https://github.com/NixOS/nixpkgs/archive/master.tar.gz --query --available

Name

nix-env --rollback - set user environment to previous generation

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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

Name

nix-env --set-flag - modify meta attributes of installed packages

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 clashes. 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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

To prevent the currently installed Firefox from being upgraded:

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

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

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

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

$ nix-env --preserve-installed --install 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 --install firefox-2.0.0.11
installing `firefox-2.0.0.11'

$ nix-env --query
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

Name

nix-env --set - set profile to contain a specified derivation

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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

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

Name

nix-env --switch-generation - set user environment to given profile 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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

Name

nix-env --switch-profile - set user environment to given 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.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

$ nix-env --switch-profile ~/my-profile

Name

nix-env --uninstall - remove packages from user environment

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 drvnames are removed.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

Name

nix-env --upgrade - upgrade packages in user environment

Synopsis

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

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.

  • --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 clashes between the two versions. However, this is not the case for all packages.

Options

The following options are allowed for all nix-env operations, but may not always have an effect.

  • --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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_PROFILE

    Location of the Nix profile. Defaults to the target of the symlink ~/.nix-profile, if it exists, or /nix/var/nix/profiles/default otherwise.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

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

When there are no updates available, nothing will happen:

$ nix-env --upgrade --attr nixpkgs.pan

Using -A is preferred when possible, as it is faster and unambiguous but it is also possible to upgrade to a specific version by matching the derivation name:

$ nix-env --upgrade gcc-3.3.2 --always
upgrading `gcc-3.4' to `gcc-3.3.2'

To try to upgrade everything (matching packages based on the part of the derivation name without version):

$ nix-env --upgrade
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 followed by a letter. y is considered an upgrade of x if their package names match, and the version of y is higher than 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

Utilities

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

Name

nix-collect-garbage - delete unreachable store objects

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 store objects in the Nix store to clean up your system.

However, it provides two additional options, --delete-old and --delete-older-than, which also delete old profiles, allowing potentially more store objects to be deleted because profiles are also garbage collection roots. These options are the equivalent of running nix-env --delete-generations with various augments on multiple profiles, prior to running nix-collect-garbage (or just nix-store --gc) without any flags.

Note

Deleting previous configurations makes rollbacks to them impossible.

These flags should be used with care, because they potentially delete generations of profiles used by other users on the system.

Locations searched for profiles

nix-collect-garbage cannot know about all profiles; that information doesn't exist. Instead, it looks in a few locations, and acts on all profiles it finds there:

  1. The default profile locations as specified in the profiles section of the manual.

  2. NOTE

    Not stable; subject to change

    Do not rely on this functionality; it just exists for migration purposes and may change in the future. These deprecated paths remain a private implementation detail of Nix.

    $NIX_STATE_DIR/profiles and $NIX_STATE_DIR/profiles/per-user.

    With the exception of $NIX_STATE_DIR/profiles/per-user/root and $NIX_STATE_DIR/profiles/default, these directories are no longer used by other commands. nix-collect-garbage looks there anyways in order to clean up profiles from older versions of Nix.

Options

These options are for deleting old profiles prior to deleting unreachable store objects.

  • --delete-old / -d

    Delete all old generations of profiles.

    This is the equivalent of invoking nix-env --delete-generations old on each found profile.

  • --delete-older-than period

    Delete all generations of profiles older than the specified amount (except for the generations that were active at that point in time). period is a value such as 30d, which would mean 30 days.

    This is the equivalent of invoking nix-env --delete-generations <period> on each found profile. See the documentation of that command for additional information about the period argument.

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

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

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 store objects to or from a remote machine via SSH

Synopsis

nix-copy-closure [--to | --from ] [--gzip] [--include-outputs] [--use-substitutes | -s] [-v] [user@]machine[:port] paths

Description

Given paths from one machine, nix-copy-closure computes the closure of those paths (i.e. all their dependencies in the Nix store), and copies store objects in that closure to another machine via SSH. It doesn’t copy store objects that are already present on the other machine.

Note

While the Nix store to use on the local machine can be specified on the command line with the --store option, the Nix store to be accessed on the remote machine can only be configured statically on that remote machine.

Since nix-copy-closure calls ssh, you may need to authenticate with the remote machine. In fact, you may be asked for authentication 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. When using public key authentication, you can avoid typing the passphrase with ssh-agent.

Options

  • --to

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

  • --from

    Copy the closure of paths from the Nix store on the remote machine to the local machine's specified 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 store objects on the target from substituters. Any store objects 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 cache.nixos.org (the default binary cache server) is fast.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

Environment variables

  • NIX_SSHOPTS

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

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

Example

Copy GNU Hello with all its dependencies to a remote machine:

$ storePath="$(nix-build '<nixpkgs>' -I nixpkgs=channel:nixpkgs-unstable -A hello --no-out-link)"
$ nix-copy-closure --to alice@itchy.example.org "$storePath"
copying 5 paths...
copying path '/nix/store/nrwkk6ak3rgkrxbqhsscb01jpzmslf2r-xgcc-13.2.0-libgcc' to 'ssh://alice@itchy.example.org'...
copying path '/nix/store/gm61h1y42pqyl6178g90x8zm22n6pyy5-libunistring-1.1' to 'ssh://alice@itchy.example.org'...
copying path '/nix/store/ddfzjdykw67s20c35i7a6624by3iz5jv-libidn2-2.3.7' to 'ssh://alice@itchy.example.org'...
copying path '/nix/store/apab5i73dqa09wx0q27b6fbhd1r18ihl-glibc-2.39-31' to 'ssh://alice@itchy.example.org'...
copying path '/nix/store/g1n2vryg06amvcc1avb2mcq36faly0mh-hello-2.12.1' to 'ssh://alice@itchy.example.org'...

Example

Copy GNU Hello from a remote machine using a known store path, and run it:

$ storePath="$(nix-instantiate --eval --raw '<nixpkgs>' -I nixpkgs=channel:nixpkgs-unstable -A hello.outPath)"
$ nix-copy-closure --from alice@itchy.example.org "$storePath"
$ "$storePath"/bin/hello
Hello, world!

Name

nix-daemon - Nix multi-user support daemon

Synopsis

nix-daemon

Description

The Nix daemon is necessary in multi-user Nix installations. It runs build tasks 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 hashAlgo] path…

nix-hash [--to-base16|--to-base32|--to-base64|--to-sri] [--type hashAlgo] 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 Nix Archive (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, instead of computing the hash of the Nix Archive (NAR) of path, just [directly hash]((../store/file-system-object/content-address.md#serial-flat) path as is. This requires path to resolve to a regular file rather than directory. The result is identical to that produced by the GNU commands md5sum and sha1sum.

  • --base16

    Print the hash in a hexadecimal representation (default).

  • --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).

  • --base64

    Similar to --base32, but print the hash in a base-64 representation, which is more compact than the base-32 one.

  • --sri

    Print the hash in SRI format with base-64 encoding. The type of hash algorithm will be prepended to the hash string, followed by a hyphen (-) and the base-64 hash body.

  • --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 blake3, md5, sha1, sha256, and sha512.

  • --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.

  • --to-base64

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

  • --to-sri

    Don’t hash anything, but convert the hexadecimal hash representation hash to SRI.

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 --base16 test/
e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6

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

$ nix-hash --type sha1 --base64 test/
5P2Lpfe76upazon+ECVVNs1g2rY=

$ nix-hash --type sha1 --sri test/
sha1-5P2Lpfe76upazon+ECVVNs1g2rY=

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

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

Converting between hexadecimal, base-32, base-64, and SRI:

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

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

$ nix-hash --type sha1 --to-base64 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6
5P2Lpfe76upazon+ECVVNs1g2rY=

$ nix-hash --type sha1 --to-sri nvd61k9nalji1zl9rrdfmsmvyyjqpzg4
sha1-5P2Lpfe76upazon+ECVVNs1g2rY=

$ nix-hash --to-base16 sha1-5P2Lpfe76upazon+ECVVNs1g2rY=
e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6

Name

nix-instantiate - instantiate store derivations from Nix expressions

Synopsis

nix-instantiate [--parse | --eval [--strict] [--raw | --json | --xml] ] [--read-write-mode] [--arg name value] [{--attr| -A} attrPath] [--add-root path] [--expr | -E] files…

nix-instantiate --find-file files…

Description

The command nix-instantiate produces 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.

Options

  • --add-root path

    See the corresponding option in nix-store.

  • --parse

    Just parse the input files, and print their abstract syntax trees on standard output as a Nix expression.

  • --eval

    Just parse and evaluate the input files, and print the resulting values on standard output. Store derivations are not serialized and written to the store, but instead just hashed and discarded.

    Warning

    This option produces output which can be parsed as a Nix expression which will produce a different result than the input expression when evaluated. For example, these two Nix expressions print the same result despite having different meaning:

    $ nix-instantiate --eval --expr '{ a = {}; }'
    { a = <CODE>; }
    $ nix-instantiate --eval --expr '{ a = <CODE>; }'
    { a = <CODE>; }
    

    For human-readable output, nix eval (experimental) is more informative:

    $ nix-instantiate --eval --expr 'a: a'
    <LAMBDA>
    $ nix eval --expr 'a: a'
    «lambda @ «string»:1:1»
    

    For machine-readable output, the --xml option produces unambiguous output:

    $ nix-instantiate --eval --xml --expr '{ foo = <CODE>; }'
    <?xml version='1.0' encoding='utf-8'?>
    <expr>
      <attrs>
        <attr column="3" line="1" name="foo">
          <unevaluated />
        </attr>
      </attrs>
    </expr>
    
  • --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, if NIX_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 language is lazy).

    Warning

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

  • --raw

    When used with --eval, the evaluation result must be a string, which is printed verbatim, without quoting, escaping or trailing newline.

  • --json

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

  • --xml

    When used with --eval, print the resulting value as an XML representation of the abstract syntax tree rather than as a Nix expression. 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.

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.

  • --log-format format

    This option can be used to change the output of the log format, with format being one of:

    • raw

      This is the raw format, as outputted by nix-build.

    • internal-json

      Outputs the logs in a structured manner.

      Warning

      While the schema itself is relatively stable, the format of the error-messages (namely of the msg-field) can change between releases.

    • bar

      Only display a progress bar during the builds.

    • bar-with-logs

      Display the raw logs, with the progress bar at the bottom.

  • --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.

    Setting it to 0 disallows building on the local machine, which is useful when you want builds to happen only on remote builders.

  • --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 cores configuration 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-time configuration 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).

  • --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-env, nix-instantiate, nix-shell 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 --install --attr 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 --install --attr pkgname --arg system \"i686-freebsd\". (Note that since the argument is a Nix string literal, you have to escape the quotes.)

  • --arg-from-file name path

    Pass the contents of file path as the argument name to Nix functions.

  • --arg-from-stdin name

    Pass the contents of stdin as the argument name to Nix functions.

  • --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-env, nix-instantiate, nix-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.

  • --eval-store store-url

    The URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and inputs referenced by them.

  • --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-instantiate, nix-build and nix-shell only.)

    For nix-shell, this option is commonly used to give you a shell in which you can build the packages returned by the expression. If you want to get a shell which contain the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead.

  • -I / --include path

    Add an entry to the list of search paths used to resolve lookup paths. This option may be given multiple times.

    Paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable.

  • --impure

    Allow access to mutable paths and repositories.

  • --option name value

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

  • --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.

Note

See man nix.conf for overriding configuration settings with command line flags.

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. It can have the values pure or impure.

  • NIX_PATH

    A colon-separated list of search path entries used to resolve lookup paths.

    This environment variable overrides the value of the nix-path configuration setting.

    It can be extended using the -I option.

    Example

    $ export NIX_PATH=`/home/eelco/Dev:nixos-config=/etc/nixos
    

    If NIX_PATH is set to an empty string, resolving search paths will always fail.

    Example

    $ NIX_PATH= nix-instantiate --eval '<nixpkgs>'
    error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
    
  • 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/var/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 system Nix configuration directory (default prefix/etc/nix).

  • NIX_CONFIG

    Applies settings from Nix configuration from the environment. The content is treated as if it was read from a Nix configuration file. Settings are separated by the newline character.

  • NIX_USER_CONF_FILES

    Overrides the location of the Nix user configuration files to load from.

    The default are the locations according to the XDG Base Directory Specification. See the XDG Base Directories sub-section for details.

    The variable is treated as a list separated by the : token.

  • 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.

XDG Base Directories

Nix follows the XDG Base Directory Specification.

For backwards compatibility, Nix commands will follow the standard only when use-xdg-base-directories is enabled. New Nix commands (experimental) conform to the standard by default.

The following environment variables are used to determine locations of various state and configuration files:

In addition, setting the following environment variables overrides the XDG base directories:

When use-xdg-base-directories is enabled, the configuration directory is:

  1. $NIX_CONFIG_HOME, if it is defined
  2. Otherwise, $XDG_CONFIG_HOME/nix, if XDG_CONFIG_HOME is defined
  3. Otherwise, ~/.config/nix.

Likewise for the state and cache directories.

Examples

Instantiate store derivations from a Nix expression, and build them using nix-store:

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

$ nix-store --realise $(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 --expr 'with import <nixpkgs> { }; hello'
/nix/store/j8s4zyv75a724q38cb0r87rlczaiag4y-hello-2.8.drv

This is equivalent to:

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

Parsing and evaluating Nix expressions:

$ nix-instantiate --parse --expr '1 + 2'
1 + 2
$ nix-instantiate --eval --expr '1 + 2'
3
$ nix-instantiate --eval --xml --expr '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 --expr '{ x = {}; }'
<?xml version='1.0' encoding='utf-8'?>
<expr>
  <attrs>
    <attr column="3" line="1" name="x">
      <unevaluated />
    </attr>
  </attrs>
</expr>

$ nix-instantiate --eval --xml --strict --expr '{ x = {}; }'
<?xml version='1.0' encoding='utf-8'?>
<expr>
  <attrs>
    <attr column="3" line="1" name="x">
      <attrs>
      </attrs>
    </attr>
  </attrs>
</expr>

Name

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

Synopsis

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

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 is signaled if the actual hash of the file does not match the specified hash.

This command prints the hash on standard output. The hash is printed using base-32 unless --type md5 is specified, in which case it's printed using base-16. 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 blake3, md5, sha1, sha256, and sha512. The default is 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 or fetchFromGitHub.

  • --executable

    Set the executable bit on the downloaded file.

  • --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

Files

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

Name

nix.conf - Nix configuration file

Description

Nix supports a variety of configuration settings, which are read from configuration files or taken as command line flags.

Configuration file

By default Nix reads settings from the following places, in that order:

  1. 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.

    Values loaded in this file are not forwarded to the Nix daemon. The client assumes that the daemon has already loaded them.

  2. If NIX_USER_CONF_FILES is set, then each path separated by : will be loaded in reverse order.

    Otherwise it will look for nix/nix.conf files in XDG_CONFIG_DIRS and XDG_CONFIG_HOME. If unset, XDG_CONFIG_DIRS defaults to /etc/xdg, and XDG_CONFIG_HOME defaults to $HOME/.config as per XDG Base Directory Specification.

  3. If NIX_CONFIG is set, its contents are treated as the contents of a configuration file.

File format

Configuration files consist of name = value pairs, one per line. Comments start with a # character.

Example:

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

Other files can be included with a line like include <path>, where <path> is interpreted relative to the current configuration file. A missing file is an error unless !include is used instead.

A configuration setting usually overrides any previous value. However, for settings that take a list of items, you can prefix the name of the setting by extra- to append to the previous value.

For instance,

substituters = a b
extra-substituters = c d

defines the substituters setting to be a b c d.

Unknown option names are not an error, and are simply ignored with a warning.

Command line flags

Configuration options can be set on the command line, overriding the values set in the configuration file:

  • Every configuration setting has corresponding command line flag (e.g. --max-jobs 16). Boolean settings do not need an argument, and can be explicitly disabled with the no- prefix (e.g. --keep-failed and --no-keep-failed).

    Unknown option names are invalid flags (unless there is already a flag with that name), and are rejected with an error.

  • The flag --option <name> <value> is interpreted exactly like a <name> = <value> in a setting file.

    Unknown option names are ignored with a warning.

The extra- prefix is supported for settings that take a list of items (e.g. --extra-trusted users alice or --option extra-trusted-users alice).

Integer settings

Settings that have an integer type support the suffixes K, M, G and T. These cause the specified value to be multiplied by 2^10, 2^20, 2^30 and 2^40, respectively. For instance, --min-free 1M is equivalent to --min-free 1048576.

Available settings

  • abort-on-warn

    If set to true, builtins.warn will throw an error when logging a warning.

    This will give you a stack trace that leads to the location of the warning.

    This is useful for finding information about warnings in third-party Nix code when you can not start the interactive debugger, such as when Nix is called from a non-interactive script. See debugger-on-warn.

    Currently, a stack trace can only be produced when the debugger is enabled, or when evaluation is aborted.

    This option can be enabled by setting NIX_ABORT_ON_WARN=1 in the environment.

    Default: false

  • accept-flake-config

    Whether to accept Nix configuration settings from a flake without prompting.

    Default: false

  • access-tokens

    Access tokens used to access protected GitHub, GitLab, or other locations requiring token-based authentication.

    Access tokens are specified as a string made up of space-separated host=token values. The specific token used is selected by matching the host portion against the "host" specification of the input. The host portion may contain a path element which will match against the prefix URL for the input. (eg: github.com/org=token). The actual use of the token value is determined by the type of resource being accessed:

    • Github: the token value is the OAUTH-TOKEN string obtained as the Personal Access Token from the Github server (see https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps).

    • Gitlab: the token value is either the OAuth2 token or the Personal Access Token (these are different types tokens for gitlab, see https://docs.gitlab.com/12.10/ee/api/README.html#authentication). The token value should be type:tokenstring where type is either OAuth2 or PAT to indicate which type of token is being specified.

    Example ~/.config/nix/nix.conf:

    access-tokens = github.com=23ac...b289 gitlab.mycompany.com=PAT:A123Bp_Cd..EfG gitlab.com=OAuth2:1jklw3jk
    

    Example ~/code/flake.nix:

    input.foo = {
      type = "gitlab";
      host = "gitlab.mycompany.com";
      owner = "mycompany";
      repo = "pro";
    };
    

    This example specifies three tokens, one each for accessing github.com, gitlab.mycompany.com, and gitlab.com.

    The input.foo uses the "gitlab" fetcher, which might requires specifying the token type along with the token value.

    Default: empty

  • allow-dirty

    Whether to allow dirty Git/Mercurial trees.

    Default: true

  • allow-dirty-locks

    Whether to allow dirty inputs (such as dirty Git workdirs) to be locked via their NAR hash. This is generally bad practice since Nix has no way to obtain such inputs if they are subsequently modified. Therefore lock files with dirty locks should generally only be used for local testing, and should not be pushed to other users.

    Default: false

  • allow-import-from-derivation

    By default, Nix allows Import from Derivation.

    With this option set to false, Nix will throw an error when evaluating an expression that uses this feature, even when the required store object is readily available. This ensures that evaluation will not require any builds to take place, regardless of the state of the store.

    Default: true

  • 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 sudo or 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).

    Default: false

  • allow-symlinked-store

    If set to true, Nix will stop complaining if the store directory (typically /nix/store) contains symlink components.

    This risks making some builds "impure" because builders sometimes "canonicalise" paths by resolving all symlink components. Problems occur if those builds are then deployed to machines where /nix/store resolves to a different location from that of the build machine. You can enable this setting if you are sure you're not going to do that.

    Default: false

  • allow-unsafe-native-code-during-evaluation

    Enable built-in functions that allow executing native code.

    In particular, this adds:

    • builtins.importNative path symbol

      Opens dynamic shared object (DSO) at path, loads the function with the symbol name symbol from it and runs it. The loaded function must have the following signature:

      extern "C" typedef void (*ValueInitialiser) (EvalState & state, Value & v);
      

      The Nix C++ API documentation has more details on evaluator internals.

    • builtins.exec arguments

      Execute a program, where arguments are specified as a list of strings, and parse its output as a Nix expression.

    Default: false

  • allowed-impure-host-deps

    Which prefixes to allow derivations to ask for access to (primarily for Darwin).

    Default: empty

  • 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.

    Access is granted when

    • the URI is equal to the prefix,
    • or the URI is a subpath of the prefix,
    • or the prefix is a URI scheme ended by a colon : and the URI has the same scheme.

    Default: empty

  • allowed-users

    A list user names, separated by whitespace. These users are allowed to connect to the Nix daemon.

    You can specify groups by prefixing names with @. For instance, @wheel means all users in the wheel group. Also, you can allow all users by specifying *.

    Note

    Trusted users (set in trusted-users) can always connect to the Nix daemon.

    Default: *

  • always-allow-substitutes

    If set to true, Nix will ignore the allowSubstitutes attribute in derivations and always attempt to use available substituters.

    Default: false

  • auto-allocate-uids

    Warning

    This setting is part of an experimental feature.

    To change this setting, make sure the auto-allocate-uids experimental feature is enabled. For example, include the following in nix.conf:

    extra-experimental-features = auto-allocate-uids
    auto-allocate-uids = ...
    

    Whether to select UIDs for builds automatically, instead of using the users in build-users-group.

    UIDs are allocated starting at 872415232 (0x34000000) on Linux and 56930 on macOS.

    Default: false

  • 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.

    Default: false

  • bash-prompt

    The bash prompt (PS1) in nix develop shells.

    Default: empty

  • bash-prompt-prefix

    Prefix prepended to the PS1 environment variable in nix develop shells.

    Default: empty

  • bash-prompt-suffix

    Suffix appended to the PS1 environment variable in nix develop shells.

    Default: empty

  • build-dir

    The directory on the host, in which derivations' temporary build directories are created.

    If not set, Nix will use the system temporary directory indicated by the TMPDIR environment variable. Note that builds are often performed by the Nix daemon, so its TMPDIR is used, and not that of the Nix command line interface.

    This is also the location where --keep-failed leaves its files.

    If Nix runs without sandbox, or if the platform does not support sandboxing with bind mounts (e.g. macOS), then the builder's environment will contain this directory, instead of the virtual location sandbox-build-dir.

    Default: ``

  • build-hook

    The path to the helper program that executes remote builds.

    Nix communicates with the build hook over stdio using a custom protocol to request builds that cannot be performed directly by the Nix daemon. The default value is the internal Nix binary that implements remote building.

    Important

    Change this setting only if you really know what you’re doing.

    Default: nix __build-remote

  • build-poll-interval

    How often (in seconds) to poll for locks.

    Default: 5

  • 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 with a nix daemon accessible to untrusted clients.

    Defaults to nixbld when running as root, empty otherwise.

    Default: machine-specific

  • builders

    A semicolon- or newline-separated list of build machines.

    In addition to the usual ways of setting configuration options, the value can be read from a file by prefixing its absolute path with @.

    Example

    This is the default setting:

    builders = @/etc/nix/machines
    

    Each machine specification consists of the following elements, separated by spaces. Only the first element is required. To leave a field at its default, set it to -.

    1. The URI of the remote store in the format ssh://[username@]hostname.

      Example

      ssh://nix@mac

      For backward compatibility, ssh:// may be omitted. The hostname may be an alias defined in ~/.ssh/config.

    2. A comma-separated list of Nix system types. If omitted, this defaults to the local platform type.

      Example

      aarch64-darwin

      It is possible for a machine to support multiple platform types.

      Example

      i686-linux,x86_64-linux

    3. The SSH identity file to be used to log in to the remote machine. If omitted, SSH will use its regular identities.

      Example

      /home/user/.ssh/id_mac

    4. The maximum number of builds that Nix will execute in parallel on the machine. Typically this should be equal to the number of CPU cores.

    5. The “speed factor”, indicating the relative speed of the machine as a positive integer. If there are multiple machines of the right type, Nix will prefer the fastest, taking load into account.

    6. A comma-separated list of supported system features.

      A machine will only be used to build a derivation if all the features in the derivation's requiredSystemFeatures attribute are supported by that machine.

    7. A comma-separated list of required system features.

      A machine will only be used to build a derivation if all of the machine’s required features appear in the derivation’s requiredSystemFeatures attribute.

    8. The (base64-encoded) public host key of the remote machine. If omitted, SSH will use its regular known_hosts file.

      The value for this field can be obtained via base64 -w0.

    Example

    Multiple builders specified on the command line:

    --builders 'ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd'
    

    Example

    This specifies several machines that can perform i686-linux builds:

    nix@scratchy.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy 8 1 kvm
    nix@itchy.labs.cs.uu.nl    i686-linux /home/nix/.ssh/id_scratchy 8 2
    nix@poochie.labs.cs.uu.nl  i686-linux /home/nix/.ssh/id_scratchy 1 2 kvm benchmark
    

    However, poochie will only build derivations that have the attribute

    requiredSystemFeatures = [ "benchmark" ];
    

    or

    requiredSystemFeatures = [ "benchmark" "kvm" ];
    

    itchy cannot do builds that require kvm, but scratchy does support such builds. For regular builds, itchy will be preferred over scratchy because it has a higher speed factor.

    For Nix to use substituters, the calling user must be in the trusted-users list.

    Note

    A build machine must be accessible via SSH and have Nix installed. nix must be available in $PATH for the user connecting over SSH.

    Warning

    If you are building via the Nix daemon (default), the Nix daemon user account on the local machine (that is, root) requires access to a user account on the remote machine (not necessarily root).

    If you can’t or don’t want to configure root to be able to access the remote machine, set store to any local store, e.g. by passing --store /tmp to the command on the local machine.

    To build only on remote machines and disable local builds, set max-jobs to 0.

    If you want the remote machines to use substituters, set builders-use-substitutes to true.

    Default: machine-specific

  • builders-use-substitutes

    If set to true, Nix will instruct remote build machines to use their own substituters if available.

    It means that remote build hosts will fetch as many dependencies as possible from their own substituters (e.g, from cache.nixos.org) instead of waiting for the local machine to upload them all. This can drastically reduce build times if the network connection between the local machine and the remote build host is slow.

    Default: false

  • commit-lock-file-summary

    The commit summary to use when committing changed flake lock files. If empty, the summary is generated based on the action performed.

    Default: empty

    Deprecated alias: commit-lockfile-summary

  • 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.

    Default: true

    Deprecated alias: build-compress-log

  • connect-timeout

    The timeout (in seconds) for establishing connections in the binary cache substituter. It corresponds to curl’s --connect-timeout option. A value of 0 means no limit.

    Default: 0

  • cores

    Sets the value of the NIX_BUILD_CORES environment variable in the invocation of the builder executable of a derivation. The builder executable can use this variable to control its own maximum amount of parallelism.

    For instance, in Nixpkgs, if the attribute enableParallelBuilding for the mkDerivation build helper is set to true, it will pass the -j${NIX_BUILD_CORES} flag to GNU Make.

    The value 0 means that the builder should use all available CPU cores in the system.

    Note

    The number of parallel local Nix build jobs is independently controlled with the max-jobs setting.

    Default: machine-specific

    Deprecated alias: build-cores

  • debugger-on-trace

    If set to true and the --debugger flag is given, the following functions will enter the debugger like builtins.break.

    This is useful for debugging warnings in third-party Nix code.

    Default: false

  • debugger-on-warn

    If set to true and the --debugger flag is given, builtins.warn will enter the debugger like builtins.break.

    This is useful for debugging warnings in third-party Nix code.

    Use debugger-on-trace to also enter the debugger on legacy warnings that are logged with builtins.trace.

    Default: false

  • diff-hook

    Absolute path to an executable capable of diffing build results. The hook is executed if run-diff-hook is true, and the output of a build is known to not be the same. This program is not executed to determine if two results are the same.

    The diff hook is executed by the same user and group who ran the build. However, the diff hook does not have write access to the store path just built.

    The diff hook program receives three parameters:

    1. A path to the previous build's results

    2. A path to the current build's results

    3. The path to the build's derivation

    4. The path to the build's scratch directory. This directory will exist only if the build was run with --keep-failed.

    The stderr and stdout output from the diff hook will not be displayed to the user. Instead, it will print to the nix-daemon's log.

    When using the Nix daemon, diff-hook must be set in the nix.conf configuration file, and cannot be passed at the command line.

    Default: ``

  • download-attempts

    How often Nix will attempt to download a file before giving up.

    Default: 5

  • download-buffer-size

    The size of Nix's internal download buffer in bytes during curl transfers. If data is not processed quickly enough to exceed the size of this buffer, downloads may stall. The default is 67108864 (64 MiB).

    Default: 67108864

  • download-speed

    Specify the maximum transfer rate in kilobytes per second you want Nix to use for downloads.

    Default: 0

  • eval-cache

    Whether to use the flake evaluation cache. Certain commands won't have to evaluate when invoked for the second time with a particular version of a flake. Intermediate results are not cached.

    Default: true

  • eval-system

    This option defines builtins.currentSystem in the Nix language if it is set as a non-empty string. Otherwise, if it is defined as the empty string (the default), the value of the system configuration setting is used instead.

    Unlike system, this setting does not change what kind of derivations can be built locally. This is useful for evaluating Nix code on one system to produce derivations to be built on another type of system.

    Default: empty

  • experimental-features

    Experimental features that are enabled.

    Example:

    experimental-features = ca-derivations
    

    The following experimental features are available:

    Experimental features are further documented in the manual.

    Default: empty

  • extra-platforms

    System types of executables that can be run on this machine.

    Nix will only build a given store derivation locally when its system attribute equals any of the values specified here or in the system option.

    Setting this can be useful to build derivations locally on compatible machines:

    • i686-linux executables can be run on x86_64-linux machines (set by default)
    • x86_64-darwin executables can be run on macOS aarch64-darwin with Rosetta 2 (set by default where applicable)
    • armv6 and armv5tel executables can be run on armv7
    • some aarch64 machines can also natively run 32-bit ARM code
    • qemu-user may be used to support non-native platforms (though this may be slow and buggy)

    Build systems will usually detect the target platform to be the current physical system and therefore produce machine code incompatible with what may be intended in the derivation. You should design your derivation's builder accordingly and cross-check the results when using this option against natively-built versions of your derivation.

    Default: machine-specific

  • 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.

    Default: false

    Deprecated alias: build-fallback

  • filter-syscalls

    Whether to prevent certain dangerous system calls, such as creation of setuid/setgid files or adding ACLs or extended attributes. Only disable this if you're aware of the security implications.

    Default: true

  • flake-registry

    Path or URI of the global flake registry.

    When empty, disables the global flake registry.

    Default: https://channels.nixos.org/flake-registry.json

  • 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.

    Default: true

  • fsync-store-paths

    Whether to call fsync() on store paths before registering them, to flush them to disk. This improves robustness in case of system crashes, but reduces performance. The default is false.

    Default: false

  • gc-reserved-space

    Amount of reserved disk space for the garbage collector.

    Default: 8388608

  • hashed-mirrors

    A list of web servers used by builtins.fetchurl to obtain files by hash. Given a hash algorithm ha and a base-16 hash h, Nix will try to download the file from hashed-mirror/ha/h. This allows files to be downloaded even if they have disappeared from their original URI. For example, given an example mirror http://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.

    Default: empty

  • 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.

    Default: 25

    Deprecated alias: binary-caches-parallel-connections

  • http2

    Whether to enable HTTP/2 support.

    Default: true

  • id-count

    The number of UIDs/GIDs to use for dynamic ID allocation.

    Default: 8388608

  • ignore-try

    If set to true, ignore exceptions inside 'tryEval' calls when evaluating nix expressions in debug mode (using the --debugger flag). By default the debugger will pause on all exceptions.

    Default: false

  • ignored-acls

    A list of ACLs that should be ignored, normally Nix attempts to remove all ACLs from files and directories in the Nix store, but some ACLs like security.selinux or system.nfs4_acl can't be removed even by root. Therefore it's best to just ignore them.

    Default: security.csm security.selinux system.nfs4_acl

  • impersonate-linux-26

    Whether to impersonate a Linux 2.6 machine on newer kernels.

    Default: false

    Deprecated alias: build-impersonate-linux-26

  • impure-env

    Warning

    This setting is part of an experimental feature.

    To change this setting, make sure the configurable-impure-env experimental feature is enabled. For example, include the following in nix.conf:

    extra-experimental-features = configurable-impure-env
    impure-env = ...
    

    A list of items, each in the format of:

    • name=value: Set environment variable name to value.

    If the user is trusted (see trusted-users option), when building a fixed-output derivation, environment variables set in this option will be passed to the builder if they are listed in impureEnvVars.

    This option is useful for, e.g., setting https_proxy for fixed-output derivations and in a multi-user Nix installation, or setting private access tokens when fetching a private repository.

    Default: empty

  • json-log-path

    A path to which JSON records of Nix's log output will be written, in the same format as --log-format internal-json (without the @nix prefixes on each line).

    Default: empty

  • 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.

    Default: true

    Deprecated alias: build-keep-log

  • 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).

    Default: true

    Deprecated alias: gc-keep-derivations

  • keep-env-derivations

    If false (default), derivations are not stored in Nix user environments. That is, the derivations of 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-derivations only applies at the moment the garbage collector is run.

    Default: false

    Deprecated alias: env-keep-derivations

  • keep-failed

    Whether to keep temporary directories of failed builds.

    Default: false

  • keep-going

    Whether to keep building derivations when another build fails.

    Default: false

  • 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.

    Default: false

    Deprecated alias: gc-keep-outputs

  • log-lines

    The number of lines of the tail of the log to show if a build fails.

    Default: 25

  • 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.

    Default: 0

    Deprecated alias: build-max-log-size

  • max-call-depth

    The maximum function call depth to allow before erroring.

    Default: 10000

  • max-free

    When a garbage collection is triggered by the min-free option, it stops as soon as max-free bytes are available. The default is infinity (i.e. delete all garbage).

    Default: 9223372036854775807

  • max-jobs

    Maximum number of jobs that Nix will try to build locally in parallel.

    The special value auto causes Nix to use the number of CPUs in your system. Use 0 to disable local builds and directly use the remote machines specified in builders. This will not affect derivations that have preferLocalBuild = true, which are always built locally.

    Note

    The number of CPU cores to use for each build job is independently determined by the cores setting.

    The setting can be overridden using the --max-jobs (-j) command line switch.

    Default: 1

    Deprecated alias: build-max-jobs

  • 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-time command line switch.

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

    Default: 0

    Deprecated alias: build-max-silent-time

  • max-substitution-jobs

    This option defines the maximum number of substitution jobs that Nix will try to run in parallel. The default is 16. The minimum value one can choose is 1 and lower values will be interpreted as 1.

    Default: 16

    Deprecated alias: substitution-max-jobs

  • min-free

    When free disk space in /nix/store drops below min-free during a build, Nix performs a garbage-collection until max-free bytes are available or there is no more garbage. A value of 0 (the default) disables this feature.

    Default: 0

  • min-free-check-interval

    Number of seconds between checking free disk space.

    Default: 5

  • nar-buffer-size

    Maximum size of NARs before spilling them to disk.

    Default: 33554432

  • 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.

    Set to 0 to force updating the lookup cache.

    To wipe the lookup cache completely:

    $ rm $HOME/.cache/nix/binary-cache-v*.sqlite*
    # rm /root/.cache/nix/binary-cache-v*.sqlite*
    

    Default: 3600

  • 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.

    Default: 2592000

  • 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.

    Default: /dummy/netrc

  • nix-path

    List of search paths to use for lookup path resolution. This setting determines the value of builtins.nixPath and can be used with builtins.findFile.

    If the respective paths are accessible, the default values are:

    • $HOME/.nix-defexpr/channels

      The user channel link pointing to the current state of channels for the current user.

    • nixpkgs=$NIX_STATE_DIR/profiles/per-user/root/channels/nixpkgs

      The current state of the nixpkgs channel for the root user.

    • $NIX_STATE_DIR/profiles/per-user/root/channels

      The current state of all channels for the root user.

    These files are set up by the Nix installer. See NIX_STATE_DIR for details on the environment variable.

    Note

    If restricted evaluation is enabled, the default value is empty.

    If pure evaluation is enabled, builtins.nixPath always evaluates to the empty list [ ].

    Default: machine-specific

  • nix-shell-always-looks-for-shell-nix

    Before Nix 2.24, nix-shell would only look at shell.nix if it was in the working directory - when no file was specified.

    Since Nix 2.24, nix-shell always looks for a shell.nix, whether that's in the working directory, or in a directory that was passed as an argument.

    You may set this to false to temporarily revert to the behavior of Nix 2.23 and older.

    Using this setting is not recommended. It will be deprecated and removed.

    Default: true

  • nix-shell-shebang-arguments-relative-to-script

    Before Nix 2.24, relative file path expressions in arguments in a nix-shell shebang were resolved relative to the working directory.

    Since Nix 2.24, nix-shell resolves these paths in a manner that is relative to the base directory, defined as the script's directory.

    You may set this to false to temporarily revert to the behavior of Nix 2.23 and older.

    Using this setting is not recommended. It will be deprecated and removed.

    Default: true

  • plugin-files

    A list of plugin files to be loaded by Nix. Each of these files will be dlopened by Nix. If they contain the symbol nix_plugin_entry(), this symbol will be called. Alternatively, they can 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.

    Warning! These APIs are inherently unstable and may change from release to release.

    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).

    Default: empty

  • post-build-hook

    Optional. The path to a program to execute after each build.

    This option is only settable in the global nix.conf, or on the command line by trusted users.

    When using the nix-daemon, the daemon executes the hook as root. If the nix-daemon is not involved, the hook runs as the user executing the nix-build.

    • The hook executes after an evaluation-time build.

    • The hook does not execute on substituted paths.

    • The hook's output always goes to the user's terminal.

    • If the hook fails, the build succeeds but no further builds execute.

    • The hook executes synchronously, and blocks other builds from progressing while it runs.

    The program executes with no arguments. The program's environment contains the following environment variables:

    • DRV_PATH The derivation for the built paths.

      Example: /nix/store/5nihn1a7pa8b25l9zafqaqibznlvvp3f-bash-4.4-p23.drv

    • OUT_PATHS Output paths of the built derivation, separated by a space character.

      Example: /nix/store/zf5lbh336mnzf1nlswdn11g4n2m8zh3g-bash-4.4-p23-dev /nix/store/rjxwxwv1fpn9wa2x5ssk5phzwlcv4mna-bash-4.4-p23-doc /nix/store/6bqvbzjkcp9695dq0dpl5y43nvy37pq1-bash-4.4-p23-info /nix/store/r7fng3kk3vlpdlh2idnrbn37vh4imlj2-bash-4.4-p23-man /nix/store/xfghy8ixrhz3kyy6p724iv3cxji088dx-bash-4.4-p23.

    Default: empty

  • 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.

    Default: empty

  • preallocate-contents

    Whether to preallocate files when writing objects with known size.

    Default: false

  • print-missing

    Whether to print what paths need to be built or downloaded.

    Default: true

  • pure-eval

    Pure evaluation mode ensures that the result of Nix expressions is fully determined by explicitly declared inputs, and not influenced by external state:

    Default: false

  • require-drop-supplementary-groups

    Following the principle of least privilege, Nix will attempt to drop supplementary groups when building with sandboxing.

    However this can fail under some circumstances. For example, if the user lacks the CAP_SETGID capability. Search setgroups(2) for EPERM to find more detailed information on this.

    If you encounter such a failure, setting this option to false will let you ignore it and continue. But before doing so, you should consider the security implications carefully. Not dropping supplementary groups means the build sandbox will be less restricted than intended.

    This option defaults to true when the user is root (since root usually has permissions to call setgroups) and false otherwise.

    Default: false

  • 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 signature by a trusted key. A trusted key is one listed in trusted-public-keys, or a public key counterpart to a private key stored in a file listed in secret-key-files.

    Set to false to disable signature checking and trust all non-content-addressed paths unconditionally.

    (Content-addressed paths are inherently trustworthy and thus unaffected by this configuration option.)

    Default: true

  • restrict-eval

    If set to true, the Nix evaluator will not allow access to any files outside of builtins.nixPath, or to URIs outside of allowed-uris.

    Default: false

  • run-diff-hook

    If true, enable the execution of the diff-hook program.

    When using the Nix daemon, run-diff-hook must be set in the nix.conf configuration file, and cannot be passed at the command line.

    Default: 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 true on Linux and false on all other platforms.

    Default: true

    Deprecated alias: build-use-chroot, build-use-sandbox

  • sandbox-build-dir

    Linux only

    The build directory inside the sandbox.

    This directory is backed by build-dir on the host.

    Default: /build

  • sandbox-dev-shm-size

    Linux only

    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%.

    Default: 50%

  • sandbox-fallback

    Whether to disable sandboxing when the kernel doesn't allow it.

    Default: true

  • 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-bin will 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.

    If the source is in the Nix store, then its closure will be added to the sandbox as well.

    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.

    Default: empty

    Deprecated alias: build-chroot-dirs, build-sandbox-paths

  • 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.

    Default: empty

  • show-trace

    Whether Nix should print out a stack trace in case of Nix expression evaluation errors.

    Default: false

  • ssl-cert-file

    The path of a file containing CA certificates used to authenticate https:// downloads. Nix by default will use the first of the following files that exists:

    1. /etc/ssl/certs/ca-certificates.crt
    2. /nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt

    The path can be overridden by the following environment variables, in order of precedence:

    1. NIX_SSL_CERT_FILE
    2. SSL_CERT_FILE

    Default: machine-specific

  • stalled-download-timeout

    The timeout (in seconds) for receiving data from servers during download. Nix cancels idle downloads after this timeout's duration.

    Default: 300

  • start-id

    The first UID and GID to use for dynamic ID allocation.

    Default: 872415232

  • store

    The URL of the Nix store to use for most operations. See the Store Types section of the manual for supported store types and settings.

    Default: auto

  • substitute

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

    Default: true

    Deprecated alias: build-use-substitutes

  • substituters

    A list of URLs of Nix stores to be used as substituters, separated by whitespace. A substituter is an additional store from which Nix can obtain store objects instead of building them.

    Substituters are tried based on their priority value, which each substituter can set independently. Lower value means higher priority. The default is https://cache.nixos.org, which has a priority of 40.

    At least one of the following conditions must be met for Nix to use a substituter:

    In addition, each store path should be trusted as described in trusted-public-keys

    Default: https://cache.nixos.org/

    Deprecated alias: binary-caches

  • sync-before-registering

    Whether to call sync() before registering a path as valid.

    Default: false

  • system

    The system type of the current Nix installation. Nix will only build a given store derivation locally when its system attribute equals any of the values specified here or in extra-platforms.

    The default value is set when Nix itself is compiled for the system it will run on. The following system types are widely used, as Nix is actively supported on these platforms:

    • x86_64-linux
    • x86_64-darwin
    • i686-linux
    • aarch64-linux
    • aarch64-darwin
    • armv6l-linux
    • armv7l-linux

    In general, you do not have to modify this setting. While you can force Nix to run a Darwin-specific builder executable on a Linux machine, the result would obviously be wrong.

    This value is available in the Nix language as builtins.currentSystem if the eval-system configuration option is set as the empty string.

    Default: x86_64-linux

  • system-features

    A set of system “features” supported by this machine.

    This complements the system and extra-platforms configuration options and the corresponding system attribute on derivations.

    A derivation can require system features in the requiredSystemFeatures attribute, and the machine to build the derivation must have them.

    System features are user-defined, but Nix sets the following defaults:

    • apple-virt

      Included on Darwin if virtualization is available.

    • kvm

      Included on Linux if /dev/kvm is accessible.

    • nixos-test, benchmark, big-parallel

      These historical pseudo-features are always enabled for backwards compatibility, as they are used in Nixpkgs to route Hydra builds to specific machines.

    • ca-derivations

      Included by default if the ca-derivations experimental feature is enabled.

      This system feature is implicitly required by derivations with the __contentAddressed attribute.

    • recursive-nix

      Included by default if the recursive-nix experimental feature is enabled.

    • uid-range

      On Linux, Nix can run builds in a user namespace where they run as root (UID 0) and have 65,536 UIDs available. This is primarily useful for running containers such as systemd-nspawn inside a Nix build. For an example, see tests/systemd-nspawn/nix.

      Included by default on Linux if the auto-allocate-uids setting is enabled.

    Default: machine-specific

  • tarball-ttl

    The number of seconds a downloaded tarball is considered fresh. If the cached tarball is stale, Nix will check whether it is still up to date using the ETag header. Nix will download a new version if the ETag header is unsupported, or the cached ETag doesn't match.

    Setting the TTL to 0 forces Nix to always check if the tarball is up to date.

    Nix caches tarballs in $XDG_CACHE_HOME/nix/tarballs.

    Files fetched via NIX_PATH, fetchGit, fetchMercurial, fetchTarball, and fetchurl respect this TTL.

    Default: 3600

  • 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.

    Default: 0

    Deprecated alias: build-timeout

  • trace-function-calls

    If set to true, the Nix evaluator will trace every function call. Nix will print a log message at the "vomit" level for every function entrance and function exit.

    function-trace entered undefined position at 1565795816999559622
    function-trace exited undefined position at 1565795816999581277
    function-trace entered /nix/store/.../example.nix:226:41 at 1565795253249935150
    function-trace exited /nix/store/.../example.nix:226:41 at 1565795253249941684
    

    The undefined position means the function call is a builtin.

    Use the contrib/stack-collapse.py script distributed with the Nix source code to convert the trace logs in to a format suitable for flamegraph.pl.

    Default: false

  • trace-verbose

    Whether builtins.traceVerbose should trace its first argument when evaluated.

    Default: false

  • trust-tarballs-from-git-forges

    If enabled (the default), Nix will consider tarballs from GitHub and similar Git forges to be locked if a Git revision is specified, e.g. github:NixOS/patchelf/7c2f768bf9601268a4e71c2ebe91e2011918a70f. This requires Nix to trust that the provider will return the correct contents for the specified Git revision.

    If disabled, such tarballs are only considered locked if a narHash attribute is specified, e.g. github:NixOS/patchelf/7c2f768bf9601268a4e71c2ebe91e2011918a70f?narHash=sha256-PPXqKY2hJng4DBVE0I4xshv/vGLUskL7jl53roB8UdU%3D.

    Default: true

  • trusted-public-keys

    A whitespace-separated list of public keys.

    At least one of the following condition must be met for Nix to accept copying a store object from another Nix store (such as a substituter):

    • the store object has been signed using a key in the trusted keys list
    • the require-sigs option has been set to false
    • the store URL is configured with trusted=true
    • the store object is content-addressed

    Default: cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=

    Deprecated alias: binary-cache-public-keys

  • trusted-substituters

    A list of Nix store URLs, separated by whitespace. These are not used by default, but users of the Nix daemon can enable them by specifying substituters.

    Unprivileged users (those set in only allowed-users but not trusted-users) can pass as substituters only those URLs listed in trusted-substituters.

    Default: empty

    Deprecated alias: trusted-binary-caches

  • trusted-users

    A list of user names, separated by whitespace. These users will have additional rights when connecting to the Nix daemon, such as the ability to specify additional substituters, or to import unsigned realisations or unsigned input-addressed store objects.

    You can also specify groups by prefixing names with @. For instance, @wheel means all users in the wheel group.

    Warning

    Adding a user to trusted-users is essentially equivalent to giving that user root access to the system. For example, the user can access or replace store path contents that are critical for system security.

    Default: root

  • upgrade-nix-store-path-url

    Used by nix upgrade-nix, the URL of the file that contains the store paths of the latest Nix release.

    Default: https://github.com/NixOS/nixpkgs/raw/master/nixos/modules/installer/tools/nix-fallback-paths.nix

  • use-case-hack

    Whether to enable a macOS-specific hack for dealing with file name case collisions.

    Default: false

  • use-cgroups

    Whether to execute builds inside cgroups. This is only supported on Linux.

    Cgroups are required and enabled automatically for derivations that require the uid-range system feature.

    Default: false

  • use-registries

    Whether to use flake registries to resolve flake references.

    Default: true

  • use-sqlite-wal

    Whether SQLite should use WAL mode.

    Default: true

  • use-xdg-base-directories

    If set to true, Nix will conform to the XDG Base Directory Specification for files in $HOME. The environment variables used to implement this are documented in the Environment Variables section.

    Warning This changes the location of some well-known symlinks that Nix creates, which might break tools that rely on the old, non-XDG-conformant locations.

    In particular, the following locations change:

    OldNew
    ~/.nix-profile$XDG_STATE_HOME/nix/profile
    ~/.nix-defexpr$XDG_STATE_HOME/nix/defexpr
    ~/.nix-channels$XDG_STATE_HOME/nix/channels

    If you already have Nix installed and are using profiles or channels, you should migrate manually when you enable this option. If $XDG_STATE_HOME is not set, use $HOME/.local/state/nix instead of $XDG_STATE_HOME/nix. This can be achieved with the following shell commands:

    nix_state_home=${XDG_STATE_HOME-$HOME/.local/state}/nix
    mkdir -p $nix_state_home
    mv $HOME/.nix-profile $nix_state_home/profile
    mv $HOME/.nix-defexpr $nix_state_home/defexpr
    mv $HOME/.nix-channels $nix_state_home/channels
    

    Default: false

  • user-agent-suffix

    String appended to the user agent in HTTP requests.

    Default: empty

  • warn-dirty

    Whether to warn about dirty Git/Mercurial trees.

    Default: true

  • warn-large-path-threshold

    Warn when copying a path larger than this number of bytes to the Nix store (as determined by its NAR serialisation). Default is 0, which disables the warning. Set it to 1 to warn on all paths.

    Default: 0

Profiles

A directory that contains links to profiles managed by nix-env and nix profile:

  • $XDG_STATE_HOME/nix/profiles for regular users
  • $NIX_STATE_DIR/profiles/per-user/root if the user is root

A profile is a directory of symlinks to files in the Nix store.

Filesystem layout

Profiles are versioned as follows. When using a profile named path, path is a symlink to path-N-link, where N is the version of the profile. In turn, path-N-link is a symlink to a path in the Nix store. For example:

$ ls -l ~alice/.local/state/nix/profiles/profile*
lrwxrwxrwx 1 alice users 14 Nov 25 14:35 /home/alice/.local/state/nix/profiles/profile -> profile-7-link
lrwxrwxrwx 1 alice users 51 Oct 28 16:18 /home/alice/.local/state/nix/profiles/profile-5-link -> /nix/store/q69xad13ghpf7ir87h0b2gd28lafjj1j-profile
lrwxrwxrwx 1 alice users 51 Oct 29 13:20 /home/alice/.local/state/nix/profiles/profile-6-link -> /nix/store/6bvhpysd7vwz7k3b0pndn7ifi5xr32dg-profile
lrwxrwxrwx 1 alice users 51 Nov 25 14:35 /home/alice/.local/state/nix/profiles/profile-7-link -> /nix/store/mp0x6xnsg0b8qhswy6riqvimai4gm677-profile

Each of these symlinks is a root for the Nix garbage collector.

The contents of the store path corresponding to each version of the profile is a tree of symlinks to the files of the installed packages, e.g.

$ ll -R ~eelco/.local/state/nix/profiles/profile-7-link/
/home/eelco/.local/state/nix/profiles/profile-7-link/:
total 20
dr-xr-xr-x 2 root root 4096 Jan  1  1970 bin
-r--r--r-- 2 root root 1402 Jan  1  1970 manifest.nix
dr-xr-xr-x 4 root root 4096 Jan  1  1970 share

/home/eelco/.local/state/nix/profiles/profile-7-link/bin:
total 20
lrwxrwxrwx 5 root root 79 Jan  1  1970 chromium -> /nix/store/ijm5k0zqisvkdwjkc77mb9qzb35xfi4m-chromium-86.0.4240.111/bin/chromium
lrwxrwxrwx 7 root root 87 Jan  1  1970 spotify -> /nix/store/w9182874m1bl56smps3m5zjj36jhp3rn-spotify-1.1.26.501.gbe11e53b-15/bin/spotify
lrwxrwxrwx 3 root root 79 Jan  1  1970 zoom-us -> /nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927/bin/zoom-us

/home/eelco/.local/state/nix/profiles/profile-7-link/share/applications:
total 12
lrwxrwxrwx 4 root root 120 Jan  1  1970 chromium-browser.desktop -> /nix/store/4cf803y4vzfm3gyk3vzhzb2327v0kl8a-chromium-unwrapped-86.0.4240.111/share/applications/chromium-browser.desktop
lrwxrwxrwx 7 root root 110 Jan  1  1970 spotify.desktop -> /nix/store/w9182874m1bl56smps3m5zjj36jhp3rn-spotify-1.1.26.501.gbe11e53b-15/share/applications/spotify.desktop
lrwxrwxrwx 3 root root 107 Jan  1  1970 us.zoom.Zoom.desktop -> /nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927/share/applications/us.zoom.Zoom.desktop

…

Each profile version contains a manifest file:

A symbolic link to the user's current profile:

By default, this symlink points to:

  • $XDG_STATE_HOME/nix/profiles/profile for regular users
  • $NIX_STATE_DIR/profiles/per-user/root/profile for root

The PATH environment variable should include /bin subdirectory of the profile link (e.g. ~/.nix-profile/bin) for the user environment to be visible to the user. The installer sets this up by default, unless you enable use-xdg-base-directories.

manifest.nix

The manifest file records the provenance of the packages that are installed in a profile managed by nix-env.

Here is an example of how this file might look like after installing hello from Nixpkgs:

[{
  meta = {
    available = true;
    broken = false;
    changelog =
      "https://git.savannah.gnu.org/cgit/hello.git/plain/NEWS?h=v2.12.1";
    description = "A program that produces a familiar, friendly greeting";
    homepage = "https://www.gnu.org/software/hello/manual/";
    insecure = false;
    license = {
      deprecated = false;
      free = true;
      fullName = "GNU General Public License v3.0 or later";
      redistributable = true;
      shortName = "gpl3Plus";
      spdxId = "GPL-3.0-or-later";
      url = "https://spdx.org/licenses/GPL-3.0-or-later.html";
    };
    longDescription = ''
      GNU Hello is a program that prints "Hello, world!" when you run it.
      It is fully customizable.
    '';
    maintainers = [{
      email = "edolstra+nixpkgs@gmail.com";
      github = "edolstra";
      githubId = 1148549;
      name = "Eelco Dolstra";
    }];
    name = "hello-2.12.1";
    outputsToInstall = [ "out" ];
    platforms = [
      "i686-cygwin"
      "x86_64-cygwin"
      "x86_64-darwin"
      "i686-darwin"
      "aarch64-darwin"
      "armv7a-darwin"
      "i686-freebsd13"
      "x86_64-freebsd13"
      "aarch64-genode"
      "i686-genode"
      "x86_64-genode"
      "x86_64-solaris"
      "js-ghcjs"
      "aarch64-linux"
      "armv5tel-linux"
      "armv6l-linux"
      "armv7a-linux"
      "armv7l-linux"
      "i686-linux"
      "m68k-linux"
      "microblaze-linux"
      "microblazeel-linux"
      "mipsel-linux"
      "mips64el-linux"
      "powerpc64-linux"
      "powerpc64le-linux"
      "riscv32-linux"
      "riscv64-linux"
      "s390-linux"
      "s390x-linux"
      "x86_64-linux"
      "mmix-mmixware"
      "aarch64-netbsd"
      "armv6l-netbsd"
      "armv7a-netbsd"
      "armv7l-netbsd"
      "i686-netbsd"
      "m68k-netbsd"
      "mipsel-netbsd"
      "powerpc-netbsd"
      "riscv32-netbsd"
      "riscv64-netbsd"
      "x86_64-netbsd"
      "aarch64_be-none"
      "aarch64-none"
      "arm-none"
      "armv6l-none"
      "avr-none"
      "i686-none"
      "microblaze-none"
      "microblazeel-none"
      "msp430-none"
      "or1k-none"
      "m68k-none"
      "powerpc-none"
      "powerpcle-none"
      "riscv32-none"
      "riscv64-none"
      "rx-none"
      "s390-none"
      "s390x-none"
      "vc4-none"
      "x86_64-none"
      "i686-openbsd"
      "x86_64-openbsd"
      "x86_64-redox"
      "wasm64-wasi"
      "wasm32-wasi"
      "x86_64-windows"
      "i686-windows"
    ];
    position =
      "/nix/store/7niq32w715567hbph0q13m5lqna64c1s-nixos-unstable.tar.gz/nixos-unstable.tar.gz/pkgs/applications/misc/hello/default.nix:34";
    unfree = false;
    unsupported = false;
  };
  name = "hello-2.12.1";
  out = {
    outPath = "/nix/store/260q5867crm1xjs4khgqpl6vr9kywql1-hello-2.12.1";
  };
  outPath = "/nix/store/260q5867crm1xjs4khgqpl6vr9kywql1-hello-2.12.1";
  outputs = [ "out" ];
  system = "x86_64-linux";
  type = "derivation";
}]

Each element in this list corresponds to an installed package. It incorporates some attributes of the original derivation, including meta, name, out, outPath, outputs, system. This information is used by Nix for querying and updating the package.

manifest.json

The manifest file records the provenance of the packages that are installed in a profile managed by nix profile (experimental).

Here is an example of what the file might look like after installing zoom-us from Nixpkgs:

{
  "version": 1,
  "elements": [
    {
      "active": true,
      "attrPath": "legacyPackages.x86_64-linux.zoom-us",
      "originalUrl": "flake:nixpkgs",
      "storePaths": [
        "/nix/store/wbhg2ga8f3h87s9h5k0slxk0m81m4cxl-zoom-us-5.3.469451.0927"
      ],
      "uri": "github:NixOS/nixpkgs/13d0c311e3ae923a00f734b43fd1d35b47d8943a"
    },
    …
  ]
}

Each object in the array elements denotes an installed package and has the following fields:

  • originalUrl: The flake reference specified by the user at the time of installation (e.g. nixpkgs). This is also the flake reference that will be used by nix profile upgrade.

  • uri: The locked flake reference to which originalUrl resolved.

  • attrPath: The flake output attribute that provided this package. Note that this is not necessarily the attribute that the user specified, but the one resulting from applying the default attribute paths and prefixes; for instance, hello might resolve to packages.x86_64-linux.hello and the empty string to packages.x86_64-linux.default.

  • storePath: The paths in the Nix store containing the package.

  • active: Whether the profile contains symlinks to the files of this package. If set to false, the package is kept in the Nix store, but is not "visible" in the profile's symlink tree.

Architecture

This chapter describes how Nix works. It should help users understand why Nix behaves as it does, and it should help developers understand how to modify Nix and how to write similar tools.

Overview

Nix consists of hierarchical layers.

The following concept map shows its main components (rectangles), the objects they operate on (rounded rectangles), and their interactions (connecting phrases):


   .----------------.
   | Nix expression |----------.
   '----------------'          |
           |              passed to
           |                   |
+----------|-------------------|--------------------------------+
| Nix      |                   V                                |
|          |      +-------------------------+                   |
|          |      | commmand line interface |------.            |
|          |      +-------------------------+      |            |
|          |                   |                   |            |
|    evaluated by            calls              manages         |
|          |                   |                   |            |
|          |                   V                   |            |
|          |         +--------------------+        |            |
|          '-------->| language evaluator |        |            |
|                    +--------------------+        |            |
|                              |                   |            |
|                           produces               |            |
|                              |                   V            |
| +----------------------------|------------------------------+ |
| | store                      |                              | |
| |            referenced by   V       builds                 | |
| | .-------------.      .------------.      .--------------. | |
| | | build input |----->| build plan |----->| build result | | |
| | '-------------'      '------------'      '--------------' | |
| +-------------------------------------------------|---------+ |
+---------------------------------------------------|-----------+
                                                    |
                                              represented as
                                                    |
                                                    V
                                            .---------------.
                                            |     file      |
                                            '---------------'

At the top is the command line interface that drives the underlying layers.

The Nix language evaluator transforms Nix expressions into self-contained build plans, which are used to derive build results from referenced build inputs.

The command line interface and Nix expressions are what users deal with most.

Note

The Nix language itself does not have a notion of packages or configurations. As far as we are concerned here, the inputs and results of a build plan are just data.

Underlying the command line interface and the Nix language evaluator is the Nix store, a mechanism to keep track of build plans, data, and references between them. It can also execute build plans to produce new data, which are made available to the operating system as files.

A build plan itself is a series of build tasks, together with their build inputs.

Important A build task in Nix is called store derivation.

Each build task has a special build input executed as build instructions in order to perform the build. The result of a build task can be input to another build task.

The following data flow diagram shows a build plan for illustration. Build inputs used as instructions to a build task are marked accordingly:

+--------------------------------------------------------------------+
| build plan                                                         |
|                                                                    |
| .-------------.                                                    |
| | build input |---------.                                          |
| '-------------'         |                                          |
|                    instructions                                    |
|                         |                                          |
|                         v                                          |
| .-------------.    .----------.                                    |
| | build input |-->( build task )-------.                           |
| '-------------'    '----------'        |                           |
|                                  instructions                      |
|                                        |                           |
|                                        v                           |
| .-------------.                  .----------.     .--------------. |
| | build input |---------.       ( build task )--->| build result | |
| '-------------'         |        '----------'     '--------------' |
|                    instructions        ^                           |
|                         |              |                           |
|                         v              |                           |
| .-------------.    .----------.        |                           |
| | build input |-->( build task )-------'                           |
| '-------------'    '----------'                                    |
|                         ^                                          |
|                         |                                          |
|                         |                                          |
| .-------------.         |                                          |
| | build input |---------'                                          |
| '-------------'                                                    |
|                                                                    |
+--------------------------------------------------------------------+

Protocols

This chapter documents various developer-facing interfaces provided by Nix.

JSON Formats

Store object info JSON format

Info about a [store object].

Impure fields

These are not intrinsic properties of the store object. In other words, the same store object residing in different store could have different values for these properties.

  • deriver:

    If known, the path to the store derivation from which this store object was produced. Otherwise null.

  • registrationTime (optional):

    If known, when this derivation was added to the store. Otherwise null.

  • ultimate:

    Whether this store object is trusted because we built it ourselves, rather than substituted a build product from elsewhere.

  • signatures:

    Signatures claiming that this store object is what it claims to be. Not relevant for content-addressed store objects, but useful for input-addressed store objects.

.narinfo extra fields

This meta data is specific to the "binary cache" family of Nix store types. This information is not intrinsic to the store object, but about how it is stored.

  • url:

    Where to download a compressed archive of the file system objects of this store object.

  • compression:

    The compression format that the archive is in.

  • fileHash:

    A digest for the compressed archive itself, as opposed to the data contained within.

  • fileSize:

    The size of the compressed archive itself.

Computed closure fields

These fields are not stored at all, but computed by traversing the other fields across all the store objects in a closure.

  • closureSize:

    The total size of the compressed archive itself for this object, and the compressed archive of every object in this object's closure.

.narinfo extra fields

  • closureSize:

    The total size of this store object and every other object in its closure.

Derivation JSON Format

The JSON serialization of a derivations is a JSON object with the following fields:

  • name: The name of the derivation. This is used when calculating the store paths of the derivation's outputs.

  • outputs: Information about the output paths of the derivation. This is a JSON object with one member per output, where the key is the output name and the value is a JSON object with these fields:

    • path: The output path, if it is known in advanced. Otherwise, null.

    • method: For an output which will be [content addresed], a string representing the method of content addressing that is chosen. Valid method strings are:

      Otherwise, null.

    • hashAlgo: For an output which will be [content addresed], the name of the hash algorithm used. Valid algorithm strings are:

      • blake3
      • md5
      • sha1
      • sha256
      • sha512
    • hash: For fixed-output derivations, the expected content hash in base-16.

    Example

    "outputs": {
      "out": {
        "path": "/nix/store/2543j7c6jn75blc3drf4g5vhb1rhdq29-source",
        "method": "nar",
        "hashAlgo": "sha256",
        "hash": "6fc80dcc62179dbc12fc0b5881275898f93444833d21b89dfe5f7fbcbb1d0d62"
      }
    }
    
  • inputSrcs: A list of store paths on which this derivation depends.

  • inputDrvs: A JSON object specifying the derivations on which this derivation depends, and what outputs of those derivations.

    Example

    "inputDrvs": {
      "/nix/store/6lkh5yi7nlb7l6dr8fljlli5zfd9hq58-curl-7.73.0.drv": ["dev"],
      "/nix/store/fn3kgnfzl5dzym26j8g907gq3kbm8bfh-unzip-6.0.drv": ["out"]
    }
    

    specifies that this derivation depends on the dev output of curl, and the out output of unzip.

  • system: The system type on which this derivation is to be built (e.g. x86_64-linux).

  • builder: The absolute path of the program to be executed to run the build. Typically this is the bash shell (e.g. /nix/store/r3j288vpmczbl500w6zz89gyfa4nr0b1-bash-4.4-p23/bin/bash).

  • args: The command-line arguments passed to the builder.

  • env: The environment passed to the builder.

Lockable HTTP Tarball Protocol

Tarball flakes can be served as regular tarballs via HTTP or the file system (for file:// URLs). Unless the server implements the Lockable HTTP Tarball protocol, it is the responsibility of the user to make sure that the URL always produces the same tarball contents.

An HTTP server can return an "immutable" HTTP URL appropriate for lock files. This allows users to specify a tarball flake input in flake.nix that requests the latest version of a flake (e.g. https://example.org/hello/latest.tar.gz), while flake.lock will record a URL whose contents will not change (e.g. https://example.org/hello/<revision>.tar.gz). To do so, the server must return an HTTP Link header with the rel attribute set to immutable, as follows:

Link: <flakeref>; rel="immutable"

(Note the required < and > characters around flakeref.)

flakeref must be a tarball flakeref. It can contain the tarball flake attributes narHash, rev, revCount and lastModified. If narHash is included, its value must be the [NAR hash][Nix Archive] of the unpacked tarball (as computed via nix hash path). Nix checks the contents of the returned tarball against the narHash attribute. The rev and revCount attributes are useful when the tarball flake is a mirror of a fetcher type that has those attributes, such as Git or GitHub. They are not checked by Nix.

Link: <https://example.org/hello/442793d9ec0584f6a6e82fa253850c8085bb150a.tar.gz
  ?rev=442793d9ec0584f6a6e82fa253850c8085bb150a
  &revCount=835
  &narHash=sha256-GUm8Uh/U74zFCwkvt9Mri4DSM%2BmHj3tYhXUkYpiv31M%3D>; rel="immutable"

(The linebreaks in this example are for clarity and must not be included in the actual response.)

For tarball flakes, the value of the lastModified flake attribute is defined as the timestamp of the newest file inside the tarball.

Gitea and Forgejo support

This protocol is supported by Gitea since v1.22.1 and by Forgejo since v7.0.4/v8.0.0 and can be used with the following flake URL schema:

https://<domain name>/<owner>/<repo>/archive/<reference or revison>.tar.gz

Example

# flake.nix
{
   inputs = {
     foo.url = "https://gitea.example.org/some-person/some-flake/archive/main.tar.gz";
     bar.url = "https://gitea.example.org/some-other-person/other-flake/archive/442793d9ec0584f6a6e82fa253850c8085bb150a.tar.gz";
     qux = {
       url = "https://forgejo.example.org/another-person/some-non-flake-repo/archive/development.tar.gz";
       flake = false;
     };
   };
   outputs = { foo, bar, qux }: { /* ... */ };
}

[Nix Archive]: ../store/file-system-object/content-address.md#serial-nix-archive

Complete Store Path Calculation

This is the complete specification for how [store path]s are calculated.

The format of this specification is close to Extended Backus–Naur form, but must deviate for a few things such as hash functions which we treat as bidirectional for specification purposes.

Regular users do not need to know this information --- store paths can be treated as black boxes computed from the properties of the store objects they refer to. But for those interested in exactly how Nix works, e.g. if they are reimplementing it, this information can be useful.

store path

Store path proper

store-path = store-dir "/" digest "-" name

where

  • name = the name of the store object.

  • store-dir = the store directory

  • digest = base-32 representation of the first 160 bits of a SHA-256 hash of fingerprint

    This the hash part of the store name

Fingerprint

  • fingerprint = type ":" sha256 ":" inner-digest ":" store ":" name
    

    Note that it includes the location of the store as well as the name to make sure that changes to either of those are reflected in the hash (e.g. you won't get /nix/store/<digest>-name1 and /nix/store/<digest>-name2, or /gnu/store/<digest>-name1, with equal hash parts).

  • type = one of:

    • | "text" { ":" store-path }
      

      This is for the "Text" method of content addressing store objects. The optional trailing store paths are the references of the store object.

    • | "source" { ":" store-path } [ ":self" ]
      

      This is for the "Nix Archive" method of content addressing store objects, if the hash algorithm is SHA-256. Just like in the "Text" case, we can have the store objects referenced by their paths. Additionally, we can have an optional :self label to denote self-reference.

    • | "output:" id
      

      For either the outputs built from derivations, or content-addressed store objects that are not using one of the two above cases. To be explicit about the latter, that is currently these methods:

      id is the name of the output (usually, "out"). For content-addressed store objects, id, is always "out".

  • inner-digest = base-16 representation of a SHA-256 hash of inner-fingerprint

Inner fingerprint

  • inner-fingerprint = one of the following based on type:

    • if type = "text:" ...:

      the string written to the resulting store path.

    • if type = "source:" ...:

      the hash of the Nix Archive (NAR) serialization of the file system object of the store object.

    • if type = "output:" id:

      • For input-addressed derivation outputs:

        the ATerm serialization of the derivation modulo fixed output derivations.

      • For content-addressed store paths:

        "fixed:out:" rec algo ":" hash ":"
        

        where

        • rec = one of:

          • | ""
            

            (empty string) for hashes of the flat (single file) serialization

          • | "r:"
            

            hashes of the for Nix Archive (NAR) (arbitrary file system object) serialization

          • | "git:"
            

            hashes of the Git blob/tree Merkel tree format

        • algo = "md5" | "sha1" | "sha256"
          
        • hash = base-16 representation of the path or flat hash of the contents of the path (or expected contents of the path for fixed-output derivations).

        Note that id = "out", regardless of the name part of the store path. Also note that NAR + SHA-256 must not use this case, and instead must use the type = "source:" ... case.

Historical Note

The type = "source:" ... and type = "output:out" grammars technically overlap in purpose, in that both can represent data hashed by its SHA-256 NAR serialization.

The original reason for this way of computing names was to prevent name collisions (for security). For instance, the thinking was that it shouldn't be feasible to come up with a derivation whose output path collides with the path for a copied source. The former would have an inner-fingerprint starting with output:out:, while the latter would have an inner-fingerprint starting with source:.

Since 64519cfd657d024ae6e2bb74cb21ad21b886fd2a (2008), however, it was decided that separating derivation-produced vs manually-hashed content-addressed data like this was not useful. Now, data that is content-addressed with SHA-256 + NAR-serialization always uses the source:... construction, regardless of how it was produced (manually or by derivation). This allows freely switching between using fixed-output derivations for fetching, and fetching out-of-band and then manually adding. It also removes the ambiguity from the grammar.

Nix Archive (NAR) format

This is the complete specification of the Nix Archive format. The Nix Archive format closely follows the abstract specification of a file system object tree, because it is designed to serialize exactly that data structure.

The format of this specification is close to Extended Backus–Naur form, with the exception of the str(..) function / parameterized rule, which length-prefixes and pads strings. This makes the resulting binary format easier to parse.

Regular users do not need to know this information. But for those interested in exactly how Nix works, e.g. if they are reimplementing it, this information can be useful.

nar = str("nix-archive-1"), nar-obj;

nar-obj = str("("), nar-obj-inner, str(")");

nar-obj-inner
  = str("type"), str("regular") regular
  | str("type"), str("symlink") symlink
  | str("type"), str("directory") directory
  ;

regular = [ str("executable"), str("") ], str("contents"), str(contents);

symlink = str("target"), str(target);

(* side condition: directory entries must be ordered by their names *)
directory = { directory-entry };

directory-entry = str("entry"), str("("), str("name"), str(name), str("node"), nar-obj, str(")");

The str function / parameterized rule is defined as follows:

  • str(s) = int(|s|), pad(s);

  • int(n) = the 64-bit little endian representation of the number n

  • pad(s) = the byte sequence s, padded with 0s to a multiple of 8 byte

Derivation "ATerm" file format

For historical reasons, store derivations are stored on-disk in ATerm format.

The ATerm format used

Derivations are serialised in one of the following formats:

  • Derive(...)
    

    For all stable derivations.

  • DrvWithVersion(<version-string>, ...)
    

    The only version-strings that are in use today are for experimental features:

Use for encoding to store object

When derivation is encoded to a store object we make the following choices:

  • The store path name is the derivation name with .drv suffixed at the end

    Indeed, the ATerm format above does not contain the name of the derivation, on the assumption that a store path will also be provided out-of-band.

  • The derivation is content-addressed using the "Text" method of content-addressing derivations

Currently we always encode derivations to store object using the ATerm format (and the previous two choices), but we reserve the option to encode new sorts of derivations differently in the future.

C API

Nix provides a C API with the intent of becoming a stable API, which it is currently not. It is in development.

See:

Glossary

Development

Nix is developed on GitHub. Check the contributing guide if you want to get involved.

This chapter is a collection of guides for making changes to the code and documentation.

If you're not sure where to start, try to compile Nix from source and consider making improvements to documentation.

Building Nix

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

$ nix develop

This shell also adds ./outputs/bin/nix to your $PATH so you can run nix immediately after building it.

To get a shell with one of the other supported compilation environments:

$ nix develop .#native-clangStdenv

Note

Use ccacheStdenv to drastically improve rebuild time. By default, ccache keeps artifacts in ~/.cache/ccache/.

To build Nix itself in this shell:

[nix-shell]$ configurePhase
[nix-shell]$ buildPhase

To test it:

[nix-shell]$ checkPhase

To install it in $(pwd)/outputs:

[nix-shell]$ installPhase
[nix-shell]$ nix --version
nix (Nix) 2.12

For more information on running and filtering tests, see testing.md.

To build a release version of Nix for the current operating system and CPU architecture:

$ nix build

You can also build Nix for one of the supported platforms.

Platforms

Nix can be built for various platforms, as specified in flake.nix:

  • x86_64-linux
  • x86_64-darwin
  • i686-linux
  • aarch64-linux
  • aarch64-darwin
  • armv6l-linux
  • armv7l-linux
  • riscv64-linux

In order to build Nix for a different platform than the one you're currently on, you need a way for your current Nix installation to build code for that platform. Common solutions include [remote build machines] and binary format emulation (only supported on NixOS).

Given such a setup, executing the build only requires selecting the respective attribute. For example, to compile for aarch64-linux:

$ nix build .#packages.aarch64-linux.default

Cross-compiled builds are available for:

  • armv6l-linux
  • armv7l-linux
  • riscv64-linux Add more system types to crossSystems in flake.nix to bootstrap Nix on unsupported platforms.

Building for multiple platforms at once

It is useful to perform multiple cross and native builds on the same source tree, for example to ensure that better support for one platform doesn't break the build for another. Meson thankfully makes this very easy by confining all build products to the build directory --- one simple shares the source directory between multiple build directories, each of which contains the build for Nix to a different platform.

Here's how to do that:

  1. Instruct Nixpkgs's infra where we want Meson to put its build directory

    mesonBuildDir=build-my-variant-name
    
  2. Configure as usual

    configurePhase
    
  3. Build as usual

    buildPhase
    

System type

Nix uses a string with the following format to identify the system type or platform it runs on:

<cpu>-<os>[-<abi>]

It is set when Nix is compiled for the given system, and based on the output of config.guess (upstream):

<cpu>-<vendor>-<os>[<version>][-<abi>]

When Nix is built such that ./configure is passed any of the --host, --build, --target options, the value is based on the output of config.sub (upstream):

<cpu>-<vendor>[-<kernel>]-<os>

For historic reasons and backward-compatibility, some CPU and OS identifiers are translated from the GNU Autotools naming convention in configure.ac as follows:

config.guessNix
amd64x86_64
i*86i686
arm6arm6l
arm7arm7l
linux-gnu*linux
linux-musl*linux

Compilation environments

Nix can be compiled using multiple environments:

  • stdenv: default;
  • gccStdenv: force the use of gcc compiler;
  • clangStdenv: force the use of clang compiler;
  • ccacheStdenv: enable [ccache], a compiler cache to speed up compilation.

To build with one of those environments, you can use

$ nix build .#nix-ccacheStdenv

You can use any of the other supported environments in place of nix-ccacheStdenv.

Editor integration

The clangd LSP server is installed by default on the clang-based devShells. See supported compilation environments and instructions how to set up a shell with flakes.

To use the LSP with your editor, you will want a compile_commands.json file telling clangd how we are compiling the code. Meson's configure always produces this inside the build directory.

Configure your editor to use the clangd from the .#native-clangStdenv shell. You can do that either by running it inside the development shell, or by using nix-direnv and the appropriate editor plugin.

Note

For some editors (e.g. Visual Studio Code), you may need to install a special extension for the editor to interact with clangd. Some other editors (e.g. Emacs, Vim) need a plugin to support LSP servers in general (e.g. lsp-mode for Emacs and vim-lsp for vim). Editor-specific setup is typically opinionated, so we will not cover it here in more detail.

Formatting and pre-commit hooks

You may run the formatters as a one-off using:

./maintainers/format.sh

Pre-commit hooks

If you'd like to run the formatters before every commit, install the hooks:

pre-commit-hooks-install

This installs pre-commit using cachix/git-hooks.nix.

When making a commit, pay attention to the console output. If it fails, run git add --patch to approve the suggestions and commit again.

To refresh pre-commit hook's config file, do the following:

  1. Exit the development shell and start it again by running nix develop.
  2. If you also use the pre-commit hook, also run pre-commit-hooks-install again.

VSCode

Insert the following json into your .vscode/settings.json file to configure nixfmt. This will be picked up by the Format Document command, "editor.formatOnSave", etc.

{
  "nix.formatterPath": "nixfmt",
  "nix.serverSettings": {
    "nixd": {
      "formatting": {
        "command": [
          "nixfmt"
        ],
      },
    },
    "nil": {
      "formatting": {
        "command": [
          "nixfmt"
        ],
      },
    },
  },
}

Running tests

Coverage analysis

A coverage analysis report is available online You can build it yourself:

# nix build .#hydraJobs.coverage
# xdg-open ./result/coverage/index.html

Extensive records of build metrics, such as test coverage over time, are also available online.

Unit-tests

The unit tests are defined using the googletest and rapidcheck frameworks.

Source and header layout

An example of some files, demonstrating much of what is described below

src
├── libexpr
│   ├── meson.build
│   ├── value/context.hh
│   ├── value/context.cc
│   …
│
├── tests
│   │
│   …
│   ├── libutil-tests
│   │   ├── meson.build
│   │   …
│   │   └── data
│   │       ├── git/tree.txt
│   │       …
│   │
│   ├── libexpr-test-support
│   │   ├── meson.build
│   │   └── tests
│   │       ├── value/context.hh
│   │       ├── value/context.cc
│   │       …
│   │
│   ├── libexpr-tests
│   …   ├── meson.build
│       ├── value/context.cc
│       …
…

The tests for each Nix library (libnixexpr, libnixstore, etc..) live inside a directory src/${library_name_without-nix}-test. Given an interface (header) and implementation pair in the original library, say, src/libexpr/value/context.{hh,cc}, we write tests for it in src/libexpr-tests/value/context.cc, and (possibly) declare/define additional interfaces for testing purposes in src/libexpr-test-support/tests/value/context.{hh,cc}.

Data for unit tests is stored in a data subdir of the directory for each unit test executable. For example, libnixstore code is in src/libstore, and its test data is in src/libstore-tests/data. The path to the src/${library_name_without-nix}-test/data directory is passed to the unit test executable with the environment variable _NIX_TEST_UNIT_DATA. Note that each executable only gets the data for its tests.

The unit test libraries are in src/${library_name_without-nix}-test-support. All headers are in a tests subdirectory so they are included with #include "tests/".

The use of all these separate directories for the unit tests might seem inconvenient, as for example the tests are not "right next to" the part of the code they are testing. But organizing the tests this way has one big benefit: there is no risk of any build-system wildcards for the library accidentally picking up test code that should not built and installed as part of the library.

Running tests

You can run the whole testsuite with meson test from the Meson build directory, or the tests for a specific component with meson test nix-store-tests. A environment variables that Google Test accepts are also worth knowing:

  1. GTEST_FILTER

    This is used for finer-grained filtering of which tests to run.

  2. GTEST_BRIEF

    This is used to avoid logging passing tests.

  3. GTEST_BREAK_ON_FAILURE

    This is used to create a debugger breakpoint when an assertion failure occurs.

Putting the first two together, one might run

GTEST_BRIEF=1 GTEST_FILTER='ErrorTraceTest.*' meson test nix-expr-tests -v

for short but comprensive output.

Debugging tests

For debugging, it is useful to combine the third option above with Meson's --gdb flag:

GTEST_BRIEF=1 GTEST_FILTER='Group.my-failing-test' meson test nix-expr-tests --gdb

This will:

  1. Run the unit test with GDB

  2. Run just Group.my-failing-test

  3. Stop the program when the test fails, allowing the user to then issue arbitrary commands to GDB.

Characterisation testing

See functional characterisation testing for a broader discussion of characterisation testing.

Like with the functional characterisation, _NIX_TEST_ACCEPT=1 is also used. For example:

$ _NIX_TEST_ACCEPT=1 meson test nix-store-tests -v
...
[  SKIPPED ] WorkerProtoTest.string_read
[  SKIPPED ] WorkerProtoTest.string_write
[  SKIPPED ] WorkerProtoTest.storePath_read
[  SKIPPED ] WorkerProtoTest.storePath_write
...

will regenerate the "golden master" expected result for the libnixstore characterisation tests. The characterisation tests will mark themselves "skipped" since they regenerated the expected result instead of actually testing anything.

Unit test support libraries

There are headers and code which are not just used to test the library in question, but also downstream libraries. For example, we do property testing with the rapidcheck library. This requires writing Arbitrary "instances", which are used to describe how to generate values of a given type for the sake of running property tests. Because types contain other types, Arbitrary "instances" for some type are not just useful for testing that type, but also any other type that contains it. Downstream types frequently contain upstream types, so it is very important that we share arbitrary instances so that downstream libraries' property tests can also use them.

It is important that these testing libraries don't contain any actual tests themselves. On some platforms they would be run as part of every test executable that uses them, which is redundant. On other platforms they wouldn't be run at all.

Functional tests

The functional tests reside under the tests/functional directory and are listed in tests/functional/meson.build. Each test is a bash script.

Functional tests are run during installCheck in the nix package build, as well as separately from the build, in VM tests.

Running the whole test suite

The whole test suite (functional and unit tests) can be run with:

$ checkPhase

Grouping tests

Sometimes it is useful to group related tests so they can be easily run together without running the entire test suite. Each test group is in a subdirectory of tests. For example, tests/functional/ca/meson.build defines a ca test group for content-addressing derivation outputs.

That test group can be run like this:

$ meson test --suite ca
ninja: Entering directory `/home/jcericson/src/nix/master/build'
ninja: no work to do.
[1-20/20] 🌑 nix-functional-tests:ca / ca/why-depends                                1/20 nix-functional-tests:ca / ca/nix-run                                  OK               0.16s
[2-20/20] 🌒 nix-functional-tests:ca / ca/why-depends                                2/20 nix-functional-tests:ca / ca/import-derivation                        OK               0.17s

Running individual tests

Individual tests can be run with meson:

$ meson test --verbose ${testName}
ninja: Entering directory `/home/jcericson/src/nix/master/build'
ninja: no work to do.
1/1 nix-functional-tests:main / ${testName}        OK               0.41s

Ok:                 1
Expected Fail:      0
Fail:               0
Unexpected Pass:    0
Skipped:            0
Timeout:            0

Full log written to /home/jcericson/src/nix/master/build/meson-logs/testlog.txt

The --verbose flag will make Meson also show the console output of each test for easier debugging. The test script will then be traced with set -x and the output displayed as it happens, regardless of whether the test succeeds or fails.

Tests can be also run directly without meson:

$ TEST_NAME=${testName} NIX_REMOTE='' PS4='+(${BASH_SOURCE[0]-$0}:$LINENO) tests/functional/${testName}.sh
+(${testName}.sh:1) foo
output from foo
+(${testName}.sh:2) bar
output from bar
...

Debugging failing functional tests

When a functional test fails, it usually does so somewhere in the middle of the script.

To figure out what's wrong, it is convenient to run the test regularly up to the failing nix command, and then run that command with a debugger like GDB.

For example, if the script looks like:

foo
nix blah blub
bar

edit it like so:

 foo
-nix blah blub
+gdb --args nix blah blub
 bar

Then, running the test with --interactive will prevent Meson from hijacking the terminal so you can drop you into GDB once the script reaches that point:

$ meson test ${testName} --interactive
...
+ gdb blash blub
GNU gdb (GDB) 12.1
...
(gdb)

One can debug the Nix invocation in all the usual ways. For example, enter run to start the Nix invocation.

Troubleshooting

Sometimes running tests in the development shell may leave artefacts in the local repository. To remove any traces of that:

git clean -x --force tests

Characterisation testing

Occasionally, Nix utilizes a technique called Characterisation Testing as part of the functional tests. This technique is to include the exact output/behavior of a former version of Nix in a test in order to check that Nix continues to produce the same behavior going forward.

For example, this technique is used for the language tests, to check both the printed final value if evaluation was successful, and any errors and warnings encountered.

It is frequently useful to regenerate the expected output. To do that, rerun the failed test(s) with _NIX_TEST_ACCEPT=1. For example:

_NIX_TEST_ACCEPT=1 meson test lang

This convention is shared with the characterisation unit tests too.

An interesting situation to document is the case when these tests are "overfitted". The language tests are, again, an example of this. The expected successful output of evaluation is supposed to be highly stable – we do not intend to make breaking changes to (the stable parts of) the Nix language. However, the errors and warnings during evaluation (successful or not) are not stable in this way. We are free to change how they are displayed at any time.

It may be surprising that we would test non-normative behavior like diagnostic outputs. Diagnostic outputs are indeed not a stable interface, but they still are important to users. By recording the expected output, the test suite guards against accidental changes, and ensure the result (not just the code that implements it) of the diagnostic code paths are under code review. Regressions are caught, and improvements always show up in code review.

To ensure that characterisation testing doesn't make it harder to intentionally change these interfaces, there always must be an easy way to regenerate the expected output, as we do with _NIX_TEST_ACCEPT=1.

Running functional tests on NixOS

We run the functional tests not just in the build, but also in VM tests. This helps us ensure that Nix works correctly on NixOS, and environments that have similar characteristics that are hard to reproduce in a build environment.

These can be run with:

nix build .#hydraJobs.tests.functional_user

Generally, this build is sufficient, but in nightly or CI we also test the attributes functional_root and functional_trusted, in which the test suite is run with different levels of authorization.

Integration tests

The integration tests are defined in the Nix flake under the hydraJobs.tests attribute. These tests include everything that needs to interact with external services or run Nix in a non-trivial distributed setup. Because these tests are expensive and require more than what the standard github-actions setup provides, they only run on the master branch (on https://hydra.nixos.org/jobset/nix/master).

You can run them manually with nix build .#hydraJobs.tests.{testName} or nix-build -A hydraJobs.tests.{testName}.

Installer tests

After a one-time setup, the Nix repository's GitHub Actions continuous integration (CI) workflow can test the installer each time you push to a branch.

Creating a Cachix cache for your installer tests and adding its authorisation token to GitHub enables two installer-specific jobs in the CI workflow:

  • The installer job generates installers for the platforms below and uploads them to your Cachix cache:

    • x86_64-linux
    • armv6l-linux
    • armv7l-linux
    • x86_64-darwin
  • The installer_test job (which runs on ubuntu-24.04 and macos-14) will try to install Nix with the cached installer and run a trivial Nix command.

One-time setup

  1. Have a GitHub account with a fork of the Nix repository.
  2. At cachix.org:
    • Create or log in to an account.
    • Create a Cachix cache using the format <github-username>-nix-install-tests.
    • Navigate to the new cache > Settings > Auth Tokens.
    • Generate a new Cachix auth token and copy the generated value.
  3. At github.com:
    • Navigate to your Nix fork > Settings > Secrets > Actions > New repository secret.
    • Name the secret CACHIX_AUTH_TOKEN.
    • Paste the copied value of the Cachix cache auth token.

Working on documentation

Using the CI-generated installer for manual testing

After the CI run completes, you can check the output to extract the installer URL:

  1. Click into the detailed view of the CI run.

  2. Click into any installer_test run (the URL you're here to extract will be the same in all of them).

  3. Click into the Run cachix/install-nix-action@v... step and click the detail triangle next to the first log line (it will also be Run cachix/install-nix-action@v...)

  4. Copy the value of install_url

  5. To generate an install command, plug this install_url and your GitHub username into this template:

    curl -L <install_url> | sh -s -- --tarball-url-prefix https://<github-username>-nix-install-tests.cachix.org/serve
    

Debugging Nix

This section shows how to build and debug Nix with debug symbols enabled.

Additionally, see Testing Nix for further instructions on how to debug Nix in the context of a unit test or functional test.

Building Nix with Debug Symbols

In the development shell, set the mesonBuildType environment variable to debug before configuring the build:

[nix-shell]$ export mesonBuildType=debugoptimized

Then, proceed to build Nix as described in Building Nix. This will build Nix with debug symbols, which are essential for effective debugging.

It is also possible to build without debugging for faster build:

[nix-shell]$ NIX_HARDENING_ENABLE=$(printLines $NIX_HARDENING_ENABLE | grep -v fortify)
[nix-shell]$ export mesonBuildType=debug

(The first line is needed because fortify hardening requires at least some optimization.)

Debugging the Nix Binary

Obtain your preferred debugger within the development shell:

[nix-shell]$ nix-shell -p gdb

On macOS, use lldb:

[nix-shell]$ nix-shell -p lldb

Launching the Debugger

To debug the Nix binary, run:

[nix-shell]$ gdb --args ../outputs/out/bin/nix

On macOS, use lldb:

[nix-shell]$ lldb -- ../outputs/out/bin/nix

Using the Debugger

Inside the debugger, you can set breakpoints, run the program, and inspect variables.

(gdb) break main
(gdb) run <arguments>

Refer to the GDB Documentation for comprehensive usage instructions.

On macOS, use lldb:

(lldb) breakpoint set --name main
(lldb) process launch -- <arguments>

Refer to the LLDB Tutorial for comprehensive usage instructions.

Contributing documentation

Improvements to documentation are very much appreciated, and a good way to start out with contributing to Nix.

This is how you can help:

Incremental refactorings of the documentation build setup to make it faster or easier to understand and maintain are also welcome.

Building the manual

Build the manual from scratch:

nix-build -E '(import ./.).packages.${builtins.currentSystem}.nix.doc'

or

nix build .#nix-manual

and open ./result/share/doc/nix/manual/index.html.

To build the manual incrementally, enter the development shell and run:

make manual-html-open -j $NIX_BUILD_CORES

In order to reflect changes to the Makefile for the manual, clear all generated files before re-building:

rm $(git ls-files doc/manual/ -o | grep -F '.md') && rmdir doc/manual/source/command-ref/new-cli && make manual-html -j $NIX_BUILD_CORES

Style guide

The goal of this style guide is to make it such that

  • The manual is easy to search and skim for relevant information
  • Documentation sources are easy to edit
  • Changes to documentation are easy to review

You will notice that this is not implemented consistently yet. Please follow the guide when making additions or changes to existing documentation. Do not make sweeping changes, unless they are programmatic and can be validated easily.

Language

This manual is reference documentation. The typical usage pattern is to look up isolated pieces of information. It should therefore aim to be correct, consistent, complete, and easy to navigate at a glance.

  • Aim for clarity and brevity.

    Please take the time to read the plain language guidelines for details.

  • Describe the subject factually.

    In particular, do not make value judgements or recommendations. Check the code or add tests if in doubt.

  • Provide complete, minimal examples, and explain them.

    Readers should be able to try examples verbatim and get the same results as shown in the manual. Always describe in words what a given example does.

    Non-trivial examples may need additional explanation, especially if they use concepts from outside the given context.

  • Always explain code examples in the text.

    Use comments in code samples very sparingly, for instance to highlight a particular aspect. Readers tend to glance over large amounts of code when scanning for information.

    Especially beginners will likely find reading more complex-looking code strenuous and may therefore avoid it altogether.

    If a code sample appears to require a lot of inline explanation, consider replacing it with a simpler one. If that's not possible, break the example down into multiple parts, explain them separately, and then show the combined result at the end. This should be a last resort, as that would amount to writing a tutorial on the given subject.

  • Use British English.

    This is a somewhat arbitrary choice to force consistency, and accounts for the fact that a majority of Nix users and developers are from Europe.

Reference documentation must be readable in arbitrary order. Readers cannot be expected to have any particular prerequisite knowledge about Nix. While the table of contents can provide guidance and full-text search can help, they are most likely to find what they need by following sensible cross-references.

  • Link to technical terms

    When mentioning Nix-specific concepts, commands, options, settings, etc., link to appropriate documentation. Also link to external tools or concepts, especially if their meaning may be ambiguous. You may also want to link to definitions of less common technical terms.

    Then readers won't have to actively search for definitions and are more likely to discover relevant information on their own.

    Note

    man and --help pages don't display links. Use appropriate link texts such that readers of terminal output can infer search terms.

  • Do not break existing URLs between releases.

    There are countless links in the wild pointing to old versions of the manual. We want people to find up-to-date documentation when following popular advice.

    The current setup is cumbersome, and help making better automation is appreciated.

The build checks for broken internal links with. This happens late in the process, so building the whole manual is not suitable for iterating quickly. mdbook-linkcheck does not implement checking URI fragments yet.

Markdown conventions

The manual is written in markdown, and rendered with mdBook for the web and with lowdown for man pages and --help output.

For supported markdown features, refer to:

Please observe these guidelines to ease reviews:

  • Write one sentence per line.

    This makes long sentences immediately visible, and makes it easier to review changes and make direct suggestions.

  • Use reference links – sparingly – to ease source readability. Put definitions close to their first use.

    Example:

    A [store object] contains a [file system object] and [references] to other store objects.
    
    [store object]: ../store/store-object.md
    [file system object]: ../architecture/file-system-object.md
    [references]: ../glossary.md#gloss-reference
    
  • Use admonitions of the following form:

    > **Note**
    >
    > This is a note.
    

    Highlight examples as such:

    > **Example**
    >
    > ```console
    > $ nix --version
    > ```
    

    Highlight syntax definitions as such, using EBNF notation:

    > **Syntax**
    >
    > *attribute-set* = `{` [ *attribute-name* `=` *expression* `;` ... ] `}`
    

The .. variable

.. provides a base path for links that occur in reusable snippets or other documentation that doesn't have a base path of its own.

If a broken link occurs in a snippet that was inserted into multiple generated files in different directories, use .. to reference the doc/manual/source directory.

If the .. literal appears in an error message from the mdbook-linkcheck tool, the .. replacement needs to be applied to the generated source file that mentions it. See existing .. logic in the Makefile for the manual. Regular markdown files used for the manual have a base path of their own and they can use relative paths instead of ...

API documentation

Doxygen API documentation is available online. You can also build and view it yourself:

$ nix build .#hydraJobs.internal-api-docs
$ xdg-open ./result/share/doc/nix/internal-api/html/index.html

or inside nix-shell or nix develop:

$ configurePhase
$ ninja src/internal-api-docs/html
$ xdg-open src/internal-api-docs/html/index.html

C API documentation

Note that the C API is not yet stable. C API documentation is available online. You can also build and view it yourself:

$ nix build .#hydraJobs.external-api-docs
$ xdg-open ./result/share/doc/nix/external-api/html/index.html

or inside nix-shell or nix develop:

$ configurePhase
$ ninja src/external-api-docs/html
$ xdg-open src/external-api-docs/html/index.html

CLI guideline

Goals

Purpose of this document is to provide a clear direction to help design delightful command line experience. This document contains guidelines to follow to ensure a consistent and approachable user experience.

Overview

nix command provides a single entry to a number of sub-commands that help developers and system administrators in the life-cycle of a software project. We particularly need to pay special attention to help and assist new users of Nix.

Naming the COMMANDS

Words matter. Naming is an important part of the usability. Users will be interacting with Nix on a regular basis so we should name things for ease of understanding.

We recommend following the Principle of Least Astonishment. This means that you should never use acronyms or abbreviations unless they are commonly used in other tools (e.g. nix init). And if the command name is too long (> 10-12 characters) then shortening it makes sense (e.g. “prioritization” → “priority”).

Commands should follow a noun-verb dialogue. Although noun-verb formatting seems backwards from a speaking perspective (i.e. nix store copy vs. nix copy store) it allows us to organize commands the same way users think about completing an action (the group first, then the command).

Naming rules

Rules are there to guide you by limiting your options. But not everything can fit the rules all the time. In those cases document the exceptions in Appendix 1: Commands naming exceptions and provide reason. The rules want to force a Nix developer to look, not just at the command at hand, but also the command in a full context alongside other nix commands.

$ nix [<GROUP>] <COMMAND> [<ARGUMENTS>] [<OPTIONS>]
  • GROUP, COMMAND, ARGUMENTS and OPTIONS should be lowercase and in a singular form.
  • GROUP should be a NOUN.
  • COMMAND should be a VERB.
  • ARGUMENTS and OPTIONS are discussed in Input section.

Classification

Some commands are more important, some less. While we want all of our commands to be perfect we can only spend limited amount of time testing and improving them.

This classification tries to separate commands in 3 categories in terms of their importance in regards to the new users. Users who are likely to be impacted the most by bad user experience.

  • Main commands

    Commands used for our main use cases and most likely used by new users. We expect attention to details, such as:

    Examples of such commands: nix init, nix develop, nix build, nix run, ...

  • Infrequently used commands

    From infrequently used commands we expect less attention to details, but still some:

    Examples of such commands: nix edit, nix eval, ...

  • Utility and scripting commands

    Commands that expose certain internal functionality of nix, mostly used by other scripts.

    Examples of such commands: nix store copy, nix hash base16, nix store ping, ...

Help is essential

Help should be built into your command line so that new users can gradually discover new features when they need them.

Looking for help

Since there is no standard way how user will look for help we rely on ways help is provided by commonly used tools. As a guide for this we took git and whenever in doubt look at it as a preferred direction.

The rules are:

  • Help is shown by using --help or help command (eg nix --``help or nix help).
  • For non-COMMANDs (eg. nix --``help and nix store --``help) we show a summary of most common use cases. Summary is presented on the STDOUT without any use of PAGER.
  • For COMMANDs (eg. nix init --``help or nix help init) we display the man page of that command. By default the PAGER is used (as in git).
  • At the end of either summary or man page there should be an URL pointing to an online version of more detailed documentation.
  • The structure of summaries and man pages should be the same as in git.

Anticipate where help is needed

Even better then requiring the user to search for help is to anticipate and predict when user might need it. Either because the lack of discoverability, typo in the input or simply taking the opportunity to teach the user of interesting - but less visible - details.

Shell completion

This type of help is most common and almost expected by users. We need to provide the best shell completion for bash, zsh and fish.

Completion needs to be context aware, this mean when a user types:

$ nix build n<TAB>

we need to display a list of flakes starting with n.

Wrong input

As we all know we humans make mistakes, all the time. When a typo - intentional or unintentional - is made, we should prompt for closest possible options or point to the documentation which would educate user to not make the same errors. Here are few examples:

In first example we prompt the user for typing wrong command name:

$ nix int
------------------------------------------------------------------------
  Error! Command `int` not found.
------------------------------------------------------------------------
  Did you mean:
    |> nix init
    |> nix input

Sometimes users will make mistake either because of a typo or simply because of lack of discoverability. Our handling of this cases needs to be context sensitive.

$ nix init --template=template#pyton
------------------------------------------------------------------------
  Error! Template `template#pyton` not found.
------------------------------------------------------------------------
Initializing Nix project at `/path/to/here`.
      Select a template for you new project:
          |> template#python
             template#python-pip
             template#python-poetry

Next steps

It can be invaluable to newcomers to show what a possible next steps and what is the usual development workflow with Nix. For example:

$ nix init --template=template#python
Initializing project `template#python`
          in `/home/USER/dev/new-project`

  Next steps
    |> nix develop   -- to enter development environment
    |> nix build     -- to build your project

Educate the user

We should take any opportunity to educate users, but at the same time we must be very very careful to not annoy users. There is a thin line between being helpful and being annoying.

An example of educating users might be to provide Tips in places where they are waiting.

$ nix build
    Started building my-project 1.2.3
 Downloaded python3.8-poetry 1.2.3 in 5.3 seconds
 Downloaded python3.8-requests 1.2.3 in 5.3 seconds
------------------------------------------------------------------------
      Press `v` to increase logs verbosity
         |> `?` to see other options
------------------------------------------------------------------------
      Learn something new with every build...
         |> See last logs of a build with `nix log --last` command.
------------------------------------------------------------------------
  Evaluated my-project 1.2.3 in 14.43 seconds
Downloading [12 / 200]
         |> firefox 1.2.3 [#########>       ] 10Mb/s | 2min left
   Building [2 / 20]
         |> glibc 1.2.3 -> buildPhase: <last log line>
------------------------------------------------------------------------

Now Learn part of the output is where you educate users. You should only show it when you know that a build will take some time and not annoy users of the builds that take only few seconds.

Every feature like this should go through an intensive review and testing to collect as much feedback as possible and to fine tune every little detail. If done right this can be an awesome features beginners and advance users will love, but if not done perfectly it will annoy users and leave bad impression.

Input

Input to a command is provided via ARGUMENTS and OPTIONS.

ARGUMENTS represent a required input for a function. When choosing to use ARGUMENTS over OPTIONS please be aware of the downsides that come with it:

  • User will need to remember the order of ARGUMENTS. This is not a problem if there is only one ARGUMENT.
  • With OPTIONS it is possible to provide much better auto completion.
  • With OPTIONS it is possible to provide much better error message.
  • Using OPTIONS it will mean there is a little bit more typing.

We don’t discourage the use of ARGUMENTS, but simply want to make every developer consider the downsides and choose wisely.

Naming the OPTIONS

The only naming convention - apart from the ones mentioned in Naming the COMMANDS section is how flags are named.

Flags are a type of OPTION that represent an option that can be turned ON of OFF. We can say flags are boolean type of **OPTION**.

Here are few examples of flag OPTIONS:

  • --colors vs. --no-colors (showing colors in the output)
  • --emojis vs. --no-emojis (showing emojis in the output)

Prompt when input not provided

For main commands (as per classification) we want command to improve the discoverability of possible input. A new user will most likely not know which ARGUMENTS and OPTIONS are required or which values are possible for those options.

In case the user does not provide the input or they provide wrong input, rather than show the error, prompt a user with an option to find and select correct input (see examples).

Prompting is of course not required when TTY is not attached to STDIN. This would mean that scripts won't need to handle prompt, but rather handle errors.

A place to use prompt and provide user with interactive select

$ nix init
Initializing Nix project at `/path/to/here`.
      Select a template for you new project:
          |> py
             template#python-pip
             template#python-poetry
             [ Showing 2 templates from 1345 templates ]

Another great place to add prompts are confirmation dialogues for dangerous actions. For example when adding new substitutor via OPTIONS or via flake.nix we should prompt - for the first time - and let user review what is going to happen.

$ nix build --option substitutors https://cache.example.org
------------------------------------------------------------------------
  Warning! A security related question needs to be answered.
------------------------------------------------------------------------
  The following substitutors will be used to in `my-project`:
    - https://cache.example.org

  Do you allow `my-project` to use above mentioned substitutors?
    [y/N] |> y

Output

Terminal output can be quite limiting in many ways. Which should force us to think about the experience even more. As with every design the output is a compromise between being terse and being verbose, between showing help to beginners and annoying advance users. For this it is important that we know what are the priorities.

Nix command line should be first and foremost written with beginners in mind. But users won't stay beginners for long and what was once useful might quickly become annoying. There is no golden rule that we can give in this guideline that would make it easier how to draw a line and find best compromise.

What we would encourage is to build prototypes, do some user testing and collect feedback. Then repeat the cycle few times.

First design the happy path and only after your iron it out, continue to work on edge cases (handling and displaying errors, changes of the output by certain OPTIONS, etc…)

Follow best practices

Needless to say we Nix must be a good citizen and follow best practices in command line.

In short: STDOUT is for output, STDERR is for (human) messaging.

STDOUT and STDERR provide a way for you to output messages to the user while also allowing them to redirect content to a file. For example:

$ nix build > build.txt
------------------------------------------------------------------------
  Error! Attribute `bin` missing at (1:94) from string.
------------------------------------------------------------------------

  1| with import <nixpkgs> { }; (pkgs.runCommandCC or pkgs.runCommand) "shell" { buildInputs = [ (surge.bin) ]; } ""

Because this warning is on STDERR, it doesn’t end up in the file.

But not everything on STDERR is an error though. For example, you can run nix build and collect logs in a file while still seeing the progress.

$ nix build > build.txt
  Evaluated 1234 files in 1.2 seconds
 Downloaded python3.8-poetry 1.2.3 in 5.3 seconds
 Downloaded python3.8-requests 1.2.3 in 5.3 seconds
------------------------------------------------------------------------
      Press `v` to increase logs verbosity
         |> `?` to see other options
------------------------------------------------------------------------
      Learn something new with every build...
         |> See last logs of a build with `nix log --last` command.
------------------------------------------------------------------------
  Evaluated my-project 1.2.3 in 14.43 seconds
Downloading [12 / 200]
         |> firefox 1.2.3 [#########>       ] 10Mb/s | 2min left
   Building [2 / 20]
         |> glibc 1.2.3 -> buildPhase: <last log line>
------------------------------------------------------------------------

Errors (WIP)

TODO: Once we have implementation for the happy path then we will think how to present errors.

Not only for humans

Terse, machine-readable output formats can also be useful but shouldn’t get in the way of making beautiful CLI output. When needed, commands should offer a --json flag to allow users to easily parse and script the CLI.

When TTY is not detected on STDOUT we should remove all design elements (no colors, no emojis and using ASCII instead of Unicode symbols). The same should happen when TTY is not detected on STDERR. We should not display progress / status section, but only print warnings and errors.

Dialog with the user

CLIs don't always make it clear when an action has taken place. For every action a user performs, your CLI should provide an equal and appropriate reaction, clearly highlighting the what just happened. For example:

$ nix build
 Downloaded python3.8-poetry 1.2.3 in 5.3 seconds
 Downloaded python3.8-requests 1.2.3 in 5.3 seconds
...
   Success! You have successfully built my-project.
$

Above command clearly states that command successfully completed. And in case of nix build, which is a command that might take some time to complete, it is equally important to also show that a command started.

Text alignment

Text alignment is the number one design element that will present all of the Nix commands as a family and not as separate tools glued together.

The format we should follow is:

$ nix COMMAND
   VERB_1 NOUN and other words
  VERB__1 NOUN and other words
       |> Some details

Few rules that we can extract from above example:

  • Each line should start at least with one space.
  • First word should be a VERB and must be aligned to the right.
  • Second word should be a NOUN and must be aligned to the left.
  • If you can not find a good VERB / NOUN pair, don’t worry make it as understandable to the user as possible.
  • More details of each line can be provided by |> character which is serving as the first word when aligning the text

Don’t forget you should also test your terminal output with colors and emojis off (--no-colors --no-emojis).

Dim / Bright

After comparing few terminals with different color schemes we would recommend to avoid using dimmed text. The difference from the rest of the text is very little in many terminal and color scheme combinations. Sometimes the difference is not even notable, therefore relying on it wouldn’t make much sense.

The bright text is much better supported across terminals and color schemes. Most of the time the difference is perceived as if the bright text would be bold.

Colors

Humans are already conditioned by society to attach certain meaning to certain colors. While the meaning is not universal, a simple collection of colors is used to represent basic emotions.

Colors that can be used in output

  • Red = error, danger, stop
  • Green = success, good
  • Yellow/Orange = proceed with caution, warning, in progress
  • Blue/Magenta = stability, calm

While colors are nice, when command line is used by machines (in automation scripts) you want to remove the colors. There should be a global --no-colors option that would remove the colors.

Special (Unicode) characters

Most of the terminal have good support for Unicode characters and you should use them in your output by default. But always have a backup solution that is implemented only with ASCII characters and will be used when --ascii option is going to be passed in. Please make sure that you test your output also without Unicode characters

More they showing all the different Unicode characters it is important to establish common set of characters that we use for certain situations.

Emojis

Emojis help channel emotions even better than text, colors and special characters.

We recommend keeping the set of emojis to a minimum. This will enable each emoji to stand out more.

As not everybody is happy about emojis we should provide an --no-emojis option to disable them. Please make sure that you test your output also without emojis.

Tables

All commands that are listing certain data can be implemented in some sort of a table. It’s important that each row of your output is a single ‘entry’ of data. Never output table borders. It’s noisy and a huge pain for parsing using other tools such as grep.

Be mindful of the screen width. Only show a few columns by default with the table header, for more the table can be manipulated by the following options:

  • --no-headers: Show column headers by default but allow to hide them.
  • --columns: Comma-separated list of column names to add.
  • --sort: Allow sorting by column. Allow inverse and multi-column sort as well.

Interactive output

Interactive output was selected to be able to strike the balance between beginners and advance users. While the default output will target beginners it can, with a few key strokes, be changed into and advance introspection tool.

Progress

For longer running commands we should provide and overview the progress. This is shown best in nix build example:

$ nix build
    Started building my-project 1.2.3
 Downloaded python3.8-poetry 1.2.3 in 5.3 seconds
 Downloaded python3.8-requests 1.2.3 in 5.3 seconds
------------------------------------------------------------------------
      Press `v` to increase logs verbosity
         |> `?` to see other options
------------------------------------------------------------------------
      Learn something new with every build...
         |> See last logs of a build with `nix log --last` command.
------------------------------------------------------------------------
  Evaluated my-project 1.2.3 in 14.43 seconds
Downloading [12 / 200]
         |> firefox 1.2.3 [#########>       ] 10Mb/s | 2min left
   Building [2 / 20]
         |> glibc 1.2.3 -> buildPhase: <last log line>
------------------------------------------------------------------------

Use a fzf like fuzzy search when there are multiple options to choose from.

$ nix init
Initializing Nix project at `/path/to/here`.
      Select a template for you new project:
          |> py
             template#python-pip
             template#python-poetry
             [ Showing 2 templates from 1345 templates ]

Prompt

In some situations we need to prompt the user and inform the user about what is going to happen.

$ nix build --option substitutors https://cache.example.org
------------------------------------------------------------------------
  Warning! A security related question needs to be answered.
------------------------------------------------------------------------
  The following substitutors will be used to in `my-project`:
    - https://cache.example.org

  Do you allow `my-project` to use above mentioned substitutors?
    [y/N] |> y

Verbosity

There are many ways that you can control verbosity.

Verbosity levels are:

  • ERROR (level 0)
  • WARN (level 1)
  • NOTICE (level 2)
  • INFO (level 3)
  • TALKATIVE (level 4)
  • CHATTY (level 5)
  • DEBUG (level 6)
  • VOMIT (level 7)

The default level that the command starts is ERROR. The simplest way to increase the verbosity by stacking -v option (eg: -vvv == level 3 == INFO). There are also two shortcuts, --debug to run in DEBUG verbosity level and --quiet to run in ERROR verbosity level.


Appendix 1: Commands naming exceptions

nix init and nix repl are well established

JSON guideline

Nix consumes and produces JSON in a variety of contexts. These guidelines ensure consistent practices for all our JSON interfaces, for ease of use, and so that experience in one part carries over to another.

Extensibility

The schema of JSON input and output should allow for backwards compatible extension. This section explains how to achieve this.

Two definitions are helpful here, because while JSON only defines one "key-value" object type, we use it to cover two use cases:

  • dictionary: a map from names to value that all have the same type. In C++ this would be a std::map with string keys.

  • record: a fixed set of attributes each with their own type. In C++, this would be represented by a struct.

It is best not to mix these use cases, as that may lead to incompatibilities when the schema changes. For example, adding a record field to a dictionary breaks consumers that assume all JSON object fields to have the same meaning and type, and dictionary items with a colliding name can not be represented anymore.

This leads to the following guidelines:

  • The top-level (root) value must be a record.

    Otherwise, one can not change the structure of a command's output.

  • The value of a dictionary item must be a record.

    Otherwise, the item type can not be extended.

  • List items should be records.

    Otherwise, one can not change the structure of the list items.

    If the order of the items does not matter, and each item has a unique key that is a string, consider representing the list as a dictionary instead. If the order of the items needs to be preserved, return a list of records.

  • Streaming JSON should return records.

    An example of a streaming JSON format is JSON lines, where each line represents a JSON value. These JSON values can be considered top-level values or list items, and they must be records.

Examples

This is bad, because all keys must be assumed to be store types:

{
  "local": { ... },
  "remote": { ... },
  "http": { ... }
}

This is good, because the it is extensible at the root, and is somewhat self-documenting:

{
  "storeTypes": { "local": { ... }, ... },
  "pluginSupport": true
}

While the dictionary of store types seems like a very complete response at first, a use case may arise that warrants returning additional information. For example, the presence of plugin support may be crucial information for a client to proceed when their desired store type is missing.

The following representation is bad because it is not extensible:

{ "outputs": [ "out" "bin" ] }

However, simply converting everything to records is not enough, because the order of outputs must be preserved:

{ "outputs": { "bin": {}, "out": {} } }

The first item is the default output. Deriving this information from the outputs ordering is not great, but this is how Nix currently happens to work. While it is possible for a JSON parser to preserve the order of fields, we can not rely on this capability to be present in all JSON libraries.

This representation is extensible and preserves the ordering:

{ "outputs": [ { "outputName": "out" }, { "outputName": "bin" } ] }

Self-describing values

As described in the previous section, it's crucial that schemas can be extended with new fields without breaking compatibility. However, that should not mean we use the presence/absence of fields to indicate optional information within a version of the schema. Instead, always include the field, and use null to indicate the "nothing" case.

Examples

Here are two JSON objects:

{
  "foo": {}
}
{
  "foo": {},
  "bar": {}
}

Since they differ in which fields they contain, they should not both be valid values of the same schema. At most, they can match two different schemas where the second (with foo and bar) is considered a newer version of the first (with just foo). Within each version, all fields are mandatory (always foo, and always foo and bar). Only between each version, bar gets added as a new mandatory field.

Here are another two JSON objects:

{ "foo": null }
{ "foo": { "bar": 1 } }

Since they both contain a foo field, they could be valid values of the same schema. The schema would have foo has an optional field, which is either null or an object where bar is an integer.

C++ style guide

Some miscellaneous notes on how we write C++. Formatting we hope to eventually normalize automatically, so this section is free to just discuss higher-level concerns.

The *-impl.hh pattern

Let's start with some background info first. Headers, are supposed to contain declarations, not definitions. This allows us to change a definition without changing the declaration, and have a very small rebuild during development. Templates, however, need to be specialized to use-sites. Absent fancier techniques, templates require that the definition, not just mere declaration, must be available at use-sites in order to make that specialization on the fly as part of compiling those use-sites. Making definitions available like that means putting them in headers, but that is unfortunately means we get all the extra rebuilds we want to avoid by just putting declarations there as described above.

The *-impl.hh pattern is a ham-fisted partial solution to this problem. It constitutes:

  • Declaring items only in the main foo.hh, including templates.

  • Putting template definitions in a companion foo-impl.hh header.

Most C++ developers would accompany this by having foo.hh include foo-impl.hh, to ensure any file getting the template declarations also got the template definitions. But we've found not doing this has some benefits and fewer than imagined downsides. The fact remains that headers are rarely as minimal as they could be; there is often code that needs declarations from the headers but not the templates within them. With our pattern where foo.hh doesn't include foo-impl.hh, that means they can just include foo.hh Code that needs both just includes foo.hh and foo-impl.hh. This does make linking error possible where something forgets to include foo-impl.hh that needs it, but those are build-time only as easy to fix.

This section describes the notion of experimental features, and how it fits into the big picture of the development of Nix.

What are experimental features?

Experimental features are considered unstable, which means that they can be changed or removed at any time. Users must explicitly enable them by toggling the associated experimental feature flags. This allows accessing unstable functionality without unwittingly relying on it.

Experimental feature flags were first introduced in Nix 2.4. Before that, Nix did have experimental features, but they were not guarded by flags and were merely documented as unstable. This was a source of confusion and controversy.

When should a new feature be marked experimental?

A change in the Nix codebase should be guarded by an experimental feature flag if it is considered likely to be reverted or adapted in a backwards-incompatible manner after gathering more experience with it in practice.

Examples:

  • Changes to the Nix language, such as new built-ins, syntactic or semantic changes, etc.
  • Changes to the command-line interface

Lifecycle of an experimental feature

Experimental features have to be treated on a case-by-case basis. However, the standard workflow for an experimental feature is as follows:

  • A new feature is implemented in a pull request
    • It is guarded by an experimental feature flag that is disabled by default
  • The pull request is merged, the experimental feature ends up in a release
    • Using the feature requires explicitly enabling it, signifying awareness of the potential risks
    • Being experimental, the feature can still be changed arbitrarily
  • The feature can be removed
    • The associated experimental feature flag is also removed
  • The feature can be declared stable
    • The associated experimental feature flag is removed
    • There should be enough evidence of users having tried the feature, such as feedback, fixed bugs, demonstrations of how it is put to use
    • Maintainers must feel confident that:
      • The feature is designed and implemented sensibly, that it is fit for purpose
      • Potential interactions are well-understood
      • Stabilising the feature will not incur an outsized maintenance burden in the future

The following diagram illustrates the process:

                  .------.
                  | idea |
                  '------'
                      |
       discussion, design, implementation
                      |
                      |     .-------.
                      |     |       |
                      v     v       |
               .--------------.  review
               | pull request |     |
               '--------------'     |
                   |     ^  |       |
                   |     |  '-------'
               .---'     '----.
               |              |
             merge       user feedback,
               |       (breaking) changes
               |              |
               '---.     .----'
                   |     |
                   v     |
               +--------------+
           .---| experimental |----.
           |   +--------------+    |
           |                       |
decision to stabilise      decision against
           |              keeping the feature
           |                       |
           v                       v
       +--------+             +---------+
       | stable |             | removed |
       +--------+             +---------+

Relation to the RFC process

Experimental features and RFCs both allow approaching substantial changes while minimizing the risk. However they serve different purposes:

  • An experimental feature enables developers to iterate on and deliver a new idea without committing to it or requiring a costly long-running fork. It is primarily an issue of implementation, targeting Nix developers and early testers.
  • The goal of an RFC is to make explicit all the implications of a change: Explain why it is wanted, which new use-cases it enables, which interface changes it requires, etc. It is primarily an issue of design and communication, targeting the broader community.

This means that experimental features and RFCs are orthogonal mechanisms, and can be used independently or together as needed.

Currently available experimental features

auto-allocate-uids

Allows Nix to automatically pick UIDs for builds, rather than creating nixbld* user accounts. See the auto-allocate-uids setting for details.

Refer to auto-allocate-uids tracking issue for feature tracking.

blake3-hashes

Enables support for BLAKE3 hashes.

Refer to blake3-hashes tracking issue for feature tracking.

ca-derivations

Allow derivations to be content-addressed in order to prevent rebuilds when changes to the derivation do not result in changes to the derivation's output. See __contentAddressed for details.

Refer to ca-derivations tracking issue for feature tracking.

cgroups

Allows Nix to execute builds inside cgroups. See the use-cgroups setting for details.

Refer to cgroups tracking issue for feature tracking.

configurable-impure-env

Allow the use of the impure-env setting.

Refer to configurable-impure-env tracking issue for feature tracking.

daemon-trust-override

Allow forcing trusting or not trusting clients with nix-daemon. This is useful for testing, but possibly also useful for various experiments with nix-daemon --stdio networking.

Refer to daemon-trust-override tracking issue for feature tracking.

dynamic-derivations

Allow the use of a few things related to dynamic derivations:

  • "text hashing" derivation outputs, so we can build .drv files.

  • dependencies in derivations on the outputs of derivations that are themselves derivations outputs.

Refer to dynamic-derivations tracking issue for feature tracking.

fetch-closure

Enable the use of the fetchClosure built-in function in the Nix language.

Refer to fetch-closure tracking issue for feature tracking.

fetch-tree

Enabled for Determinate Nix Installer users since 2.24

Enable the use of the fetchTree built-in function in the Nix language.

fetchTree exposes a generic interface for fetching remote file system trees from different types of remote sources. The flakes feature flag always enables fetch-tree. This built-in was previously guarded by the flakes experimental feature because of that overlap.

Enabling just this feature serves as a "release candidate", allowing users to try it out in isolation.

Refer to fetch-tree tracking issue for feature tracking.

git-hashing

Allow creating (content-addressed) store objects which are hashed via Git's hashing algorithm. These store objects will not be understandable by older versions of Nix.

Refer to git-hashing tracking issue for feature tracking.

impure-derivations

Allow derivations to produce non-fixed outputs by setting the __impure derivation attribute to true. An impure derivation can have differing outputs each time it is built.

Example:

derivation {
  name = "impure";
  builder = /bin/sh;
  __impure = true; # mark this derivation as impure
  args = [ "-c" "read -n 10 random < /dev/random; echo $random > $out" ];
  system = builtins.currentSystem;
}

Each time this derivation is built, it can produce a different output (as the builder outputs random bytes to $out). Impure derivations also have access to the network, and only fixed-output or other impure derivations can rely on impure derivations. Finally, an impure derivation cannot also be content-addressed.

This is a more explicit alternative to using builtins.currentTime.

Refer to impure-derivations tracking issue for feature tracking.

local-overlay-store

Allow the use of local overlay store.

Refer to local-overlay-store tracking issue for feature tracking.

mounted-ssh-store

Allow the use of the mounted SSH store.

Refer to mounted-ssh-store tracking issue for feature tracking.

no-url-literals

Disallow unquoted URLs as part of the Nix language syntax. The Nix language allows for URL literals, like so:

$ nix repl
Welcome to Nix 2.15.0. Type :? for help.

nix-repl> http://foo
"http://foo"

But enabling this experimental feature will cause the Nix parser to throw an error when encountering a URL literal:

$ nix repl --extra-experimental-features 'no-url-literals'
Welcome to Nix 2.15.0. Type :? for help.

nix-repl> http://foo
error: URL literals are disabled

at «string»:1:1:

1| http://foo
 | ^

While this is currently an experimental feature, unquoted URLs are being deprecated and their usage is discouraged.

The reason is that, as opposed to path literals, URLs have no special properties that distinguish them from regular strings, URLs containing parameters have to be quoted anyway, and unquoted URLs may confuse external tooling.

Refer to no-url-literals tracking issue for feature tracking.

parse-toml-timestamps

Allow parsing of timestamps in builtins.fromTOML.

Refer to parse-toml-timestamps tracking issue for feature tracking.

pipe-operators

Add |> and <| operators to the Nix language.

Refer to pipe-operators tracking issue for feature tracking.

read-only-local-store

Allow the use of the read-only parameter in local store URIs.

Refer to read-only-local-store tracking issue for feature tracking.

recursive-nix

Allow derivation builders to call Nix, and thus build derivations recursively.

Example:

with import <nixpkgs> {};

runCommand "foo"
  {
     # Optional: let Nix know "foo" requires the experimental feature
     requiredSystemFeatures = [ "recursive-nix" ];
     buildInputs = [ nix jq ];
     NIX_PATH = "nixpkgs=${<nixpkgs>}";
  }
  ''
    hello=$(nix-build -E '(import <nixpkgs> {}).hello.overrideDerivation (args: { name = "recursive-hello"; })')

    mkdir -p $out/bin
    ln -s $hello/bin/hello $out/bin/hello
  ''

An important restriction on recursive builders is disallowing arbitrary substitutions. For example, running

nix-store -r /nix/store/kmwd1hq55akdb9sc7l3finr175dajlby-hello-2.10

in the above runCommand script would be disallowed, as this could lead to derivations with hidden dependencies or breaking reproducibility by relying on the current state of the Nix store. An exception would be if /nix/store/kmwd1hq55akdb9sc7l3finr175dajlby-hello-2.10 were already in the build inputs or built by a previous recursive Nix call.

Refer to recursive-nix tracking issue for feature tracking.

verified-fetches

Enables verification of git commit signatures through the fetchGit built-in.

Refer to verified-fetches tracking issue for feature tracking.

Contributing

Add a release note

doc/manual/rl-next contains release notes entries for all unreleased changes.

User-visible changes should come with a release note.

Add an entry

Here's what a complete entry looks like. The file name is not incorporated in the document.

---
synopsis: Basically a title
issues: 1234
prs: 1238
---

Here's one or more paragraphs that describe the change.

- It's markdown
- Add references to the manual using ..

Significant changes should add the following header, which moves them to the top.

significance: significant

See also the format documentation.

Build process

Releases have a precomputed rl-MAJOR.MINOR.md, and no rl-next.md.

Branches

Reverting

If a change turns out to be merged by mistake, or contain a regression, it may be reverted. A revert is not a rejection of the contribution, but merely part of an effective development process. It makes sure that development keeps running smoothly, with minimal uncertainty, and less overhead. If maintainers have to worry too much about avoiding reverts, they would not be able to merge as much. By embracing reverts as a good part of the development process, everyone wins.

However, taking a step back may be frustrating, so maintainers will be extra supportive on the next try.

Determinate Nix Release Notes

This chapter lists the differences between Nix and Determinate Nix, as well as the release history of Determinate Nix.

Changes between Nix and Determinate Nix

This section lists the differences between upstream Nix 2.24 and Determinate Nix 3.1.0.

  • In Determinate Nix, flakes are stable. You no longer need to enable the flakes experimental feature.

  • In Determinate Nix, the new Nix CLI (i.e. the nix command) is stable. You no longer need to enable the nix-command experimental feature.

  • Determinate Nix has a setting json-log-path to send a copy of all Nix log messages (in JSON format) to a file or Unix domain socket.

Release 3.1.0 (2025-03-27)

  • Based on upstream Nix 2.27.1.

  • New setting json-log-path that sends a copy of all Nix log messages (in JSON format) to a file or Unix domain socket.

Release 3.0.0 (2025-03-04)

Nix Release Notes

The Nix release cycle is calendar-based as follows:

Nix has a release cycle of roughly 6 weeks. Notable changes and additions are announced in the release notes for each version.

The supported Nix versions are:

  • The latest release
  • The version used in the stable NixOS release, which is announced in the NixOS release notes.

Bugfixes and security issues are backported to every supported version. Patch releases are published as needed.

Release 2.27.0 (2025-03-03)

  • inputs.self.submodules flake attribute #12421

    Flakes in Git repositories can now declare that they need Git submodules to be enabled:

    {
      inputs.self.submodules = true;
    }
    

    Thus, it's no longer needed for the caller of the flake to pass submodules = true.

  • Git LFS support #10153 #12468

    The Git fetcher now supports Large File Storage (LFS). This can be enabled by passing the attribute lfs = true to the fetcher, e.g.

    nix flake prefetch 'git+ssh://git@github.com/Apress/repo-with-large-file-storage.git?lfs=1'
    

    A flake can also declare that it requires LFS to be enabled:

    {
      inputs.self.lfs = true;
    }
    

    Author: @b-camacho, @kip93

  • Handle the case where a chroot store is used and some inputs are in the "host" /nix/store #12512

    The evaluator now presents a "union" filesystem view of the /nix/store in the host and the chroot.

    This change also removes some hacks that broke builtins.{path,filterSource} in chroot stores #11503.

  • nix flake prefetch now has a --out-link option #12443

  • Set FD_CLOEXEC on sockets created by curl #12439

    Curl created sockets without setting FD_CLOEXEC/SOCK_CLOEXEC. This could previously cause connections to remain open forever when using commands like nix shell. This change sets the FD_CLOEXEC flag using a CURLOPT_SOCKOPTFUNCTION callback.

Contributors

This release was made possible by the following 21 contributors:

Release 2.26.0 (2025-01-22)

  • Support for relative path inputs #10089

    Flakes can now refer to other flakes in the same repository using relative paths, e.g.

    inputs.foo.url = "path:./foo";
    

    uses the flake in the foo subdirectory of the referring flake. For more information, see the documentation on the path flake input type.

    This feature required a change to the lock file format. Previous Nix versions will not be able to use lock files that have locks for relative path inputs in them.

  • Flake lock file generation now ignores local registries #12019

    When resolving indirect flake references like nixpkgs in flake.nix files, Nix will no longer use the system and user flake registries. It will only use the global flake registry and overrides given on the command line via --override-flake.

    This avoids accidents where users have local registry overrides that map nixpkgs to a path: flake in the local file system, which then end up in committed lock files pushed to other users.

    In the future, we may remove the use of the registry during lock file generation altogether. It's better to explicitly specify the URL of a flake input. For example, instead of

    {
      outputs = { self, nixpkgs }: { ... };
    }
    

    write

    {
      inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
      outputs = { self, nixpkgs }: { ... };
    }
    
  • nix copy supports --profile and --out-link #11657

    The nix copy command now has flags --profile and --out-link, similar to nix build. --profile makes a profile point to the top-level store path, while --out-link create symlinks to the top-level store paths.

    For example, when updating the local NixOS system profile from a NixOS system closure on a remote machine, instead of

    # nix copy --from ssh://server $path
    # nix build --profile /nix/var/nix/profiles/system $path
    

    you can now do

    # nix copy --from ssh://server --profile /nix/var/nix/profiles/system $path
    

    The advantage is that this avoids a time window where path is not a garbage collector root, and so could be deleted by a concurrent nix store gc process.

  • nix-instantiate --eval now supports --raw #12119

    The nix-instantiate --eval command now supports a --raw flag, when used the evaluation result must be a string, which is printed verbatim without quotation marks or escaping.

  • Improved NIX_SSHOPTS parsing for better SSH option handling #5181 #12020

    The parsing of the NIX_SSHOPTS environment variable has been improved to handle spaces and quotes correctly. Previously, incorrectly split SSH options could cause failures in commands like nix-copy-closure, especially when using complex SSH invocations such as -o ProxyCommand="ssh -W %h:%p ...".

    This change introduces a shellSplitString function to ensure that NIX_SSHOPTS is parsed in a manner consistent with shell behavior, addressing common parsing errors.

    For example, the following now works as expected:

    export NIX_SSHOPTS='-o ProxyCommand="ssh -W %h:%p ..."'
    

    This update improves the reliability of SSH-related operations using NIX_SSHOPTS across Nix CLIs.

  • Nix is now built using Meson

    As proposed in RFC 132, Nix's build system now uses Meson/Ninja. The old Make-based build system has been removed.

  • Evaluation caching now works for dirty Git workdirs #11992

Contributors

This release was made possible by the following 45 contributors: