NIX-STORE-EXPORT(1)

πŸ’– Name πŸ’–

nix-store --export β€” bestie, we're exporting store paths to a Nix Archive ✨

(yeah this is from the General Commands Manual, section 1, iykyk)


🌸 Synopsis 🌸

nix-store --export paths…

πŸ¦‹ Description πŸ¦‹

okay so the --export operation takes the store objects you hand it and writes a serialisation of them straight to standard output πŸ’… that serialisation is in a format you can pour right back into a different Nix store using nix-store --import 🫢

⚠️ Warning ⚠️ okay so this is the important bit, do NOT skip it: this command does not produce a closure of the store paths you specified. lowkey a trap. if you try to import a store object that refers to store paths that aren't available in the target Nix store, it's gonna fail 😭 if you actually want the closure of a store path, go get it with nix-store --query πŸ‘‘

Also, this command is not the same as nix-store --dump, bestie β€” nix-store --dump makes a Nix archive that does not contain the set of references of a given store path. different vibe entirely.

πŸŽ€ Note πŸŽ€ if you want efficient transfer of closures to remote machines over SSH, use nix-copy-closure. that's the main character for that job πŸ’«

✨ Options ✨

so these options below are allowed for all nix-store operations, but ngl they might not always have an effect πŸ™ˆ

  • --add-root path β€” makes the result of a realisation (--realise and --force-realise) get registered as a root of the garbage collector πŸ—‘οΈβœ¨ path gets created as a symlink pointing at the resulting store path. on top of that, a uniquely named symlink to path gets 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

so the way that works is: when /home/eelco/bla/result gets removed, the GC root sitting in the auto directory becomes a dangling symlink and the collector just ignores it 🧚 (slay, cleanup, no notes)

πŸ’€ Warning πŸ’€ not me telling you this the hard way: it is not possible to move or rename GC roots, because the symlink in the auto directory will still be pointing at the old location. periodt. don't try it.

and if there are multiple results? then multiple symlinks get created, by sequentially numbering symlinks beyond the first one (like foo, foo-2, foo-3, and so on) πŸ”’πŸ’…


🫢 Common Options 🫢

Okay bestie, listen β€” most Nix commands are out here sharing the same little bag of command-line options, and this is that bag. Same vibes everywhere. Let's unpack it πŸ’…

  • --help β€” prints out a summary of the command syntax and then dips. That's it, that's the whole thing. Your little emergency exit πŸšͺ
  • --version β€” prints out the Nix version number on standard output and exits. Iconic, brief, to the point.
  • --verbose, -v β€” cranks up the level of verbosity for diagnostic messages printed on standard error. And this is the important part, so pay attention: for each Nix operation, the stuff printed on standard output is well-defined β€” but any diagnostic info goes to standard error, and never to standard output. Ever. Not once.

You can pass this option over and over to keep stacking it up. Currently the verbosity levels are:

  • 0 β€œErrors only” β€” only prints messages explaining why the Nix invocation flopped. πŸ’€
  • 1 β€œInformational” β€” prints useful messages about what Nix is actually doing. This is the default, it's the vanilla vibe.
  • 2 β€œTalkative” β€” more informational messages, she's opening up.
  • 3 β€œChatty” β€” even more. She will not stop talking.
  • 4 β€œDebug” β€” prints debug information.
  • 5 β€œVomit” β€” prints vast amounts of debug information. Truly an unhinged amount. It's giving firehose 🚿
  • --quiet β€” turns the verbosity of diagnostic messages on standard error down. It's literally the inverse option to -v / --verbose. You can sprinkle it multiple times too, and it just walks back down that same verbosity levels list from above. ⬇️
  • --log-format format β€” swaps out the output of the log format, where format is one of these:
    • raw β€” the raw format, exactly as outputted by nix-build.
    • internal-json β€” outputs the logs in a structured manner.
⚠️ Warning β€” the schema itself is relatively stable, but the format of the error-messages (namely of the msg-field) can change between releases. So don't get too attached to those error strings, bestie πŸ™ˆ
  • bar β€” only displays a progress bar during the builds. Clean. Minimal. Slay.
  • bar-with-logs β€” displays the raw logs, with the progress bar chilling at the bottom.
  • --no-build-output, -Q β€” so by default, whatever output the builders write to standard output and standard error gets echoed to the Nix command's standard error. This option just suppresses that whole behaviour. But note: the builder's standard output and error are always written to a log file in prefix/nix/var/log/nix. Always. So nothing is lost, it's just not shouting in your face πŸ”‡
  • --max-jobs, -j number β€” sets the max number of build jobs Nix will run in parallel to number. Say auto to use however many CPUs the system has. The default comes from the max-jobs configuration setting, which itself defaults to 1. A higher value is useful on SMP systems, or just to exploit I/O latency. Setting it to 0 disallows building on the local machine entirely β€” super 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 however they want 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 that's set, or 1 otherwise. And the value 0 means the builder should use all available CPU cores in the system. Feed her all the cores πŸ”₯
  • --max-silent-time β€” sets the max number of seconds a builder can go without producing any data on standard output or standard error. The default comes from the max-silent-time configuration setting. 0 means no time-out, she can be quiet forever if she wants.
  • --timeout β€” sets the max number of seconds a builder is allowed to run. The default comes from the timeout configuration setting. 0 means no timeout.
  • --keep-going, -k β€” keeps going when builds fail, to the greatest extent possible. So like, if building an input of some derivation fails, Nix will still build the other inputs β€” just not that derivation itself. Without this option, Nix stops the moment any build fails (except for builds of substitutes), and it might even kill off builds that are in progress, which is extra rude when you've got parallel or distributed builds running. πŸ’…
  • --keep-failed, -K β€” says that if a build fails, the temporary directory where the build takes place (usually in /tmp) should not be deleted. The path of the build directory gets printed as an informational message so you can go poke at the crime scene πŸ”
  • --fallback β€” whenever Nix tries to build a derivation where substitutes are known for every output path, but realising those output paths through the substitutes fails, it falls back on building the derivation itself.

The most common scenario where this saves you: you've registered substitutes to do binary distribution from, say, a network repository. If that repository goes down, realising the derivation will fail. With this option on, Nix just builds the derivation instead. So installation from binaries gracefully falls back on installation from source. 🧚

This is not the default, because it's generally not desirable for a transient failure in grabbing the substitutes to snowball into a full build from source β€” and all the resource consumption that comes with it. That's the whole reason it's opt-in, bestie.

  • --readonly-mode β€” when this is used, no attempt is made to open the Nix database. And since most Nix operations genuinely need database access, those operations will just fail. So, you know. Choose wisely 🚫
  • --arg name value β€” accepted by nix-env, nix-instantiate, nix-shell and nix-build. When evaluating Nix expressions, the expression evaluator will automatically try to call functions it encounters. It can automatically call functions where 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. Basically: if the evaluator encounters a function with an argument named name, it'll call it with value for 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 gets 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. Annoying but that's the rules.)

  • --arg-from-file name path β€” passes the contents of the file path as the argument name to Nix functions.
  • --arg-from-stdin name β€” passes the contents of stdin as the argument name to Nix functions.
  • --argstr name value β€” like --arg, except the value is not a Nix expression but a string. So instead of --arg system "i686-linux" (those outer quotes exist purely to keep the shell happy), you can just say --argstr system i686-linux. So much less escaping drama πŸŽ€
  • --attr, -A attrPath β€” selects 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. Check out nix-env --install for some concrete examples.

And 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. (Fourth because it's zero-indexed, bestie, don't come for me 🌸)

  • --eval-store store-url β€” the URL to the Nix store to use for evaluation, i.e. where to store derivations (.drv files) and the inputs referenced by them.
  • --expr, -E β€” interprets the command line arguments as a list of Nix expressions to be parsed and evaluated, instead of 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. But if you want a shell that contains the built packages, ready to use, then give your expression to the nix-shell --packages convenience flag instead. Two different vibes, pick the right one ✨

  • -I, --include path β€” adds an entry to the list of search paths used to resolve lookup paths. You can give this option multiple times. And here's the power move: paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable. She jumps the queue πŸ‘‘
  • --impure β€” allows access to mutable paths and repositories. Chaos permitted.
  • --option name value β€” sets the Nix configuration option name to value. This overrides settings in the Nix configuration file (see nix.conf5).
  • --repair β€” fixes corrupted or missing store paths by redownloading or rebuilding them. Heads up though: this is slow, because it requires computing a cryptographic hash of the contents of every path in the closure of the build. Also, please note the warning under nix-store --repair-path. Don't say nobody told you 😭
πŸ“ Note β€” see man nix.conf for overriding configuration settings with command line flags.

πŸ¦‹ Common Environment Variables πŸ¦‹

okay so bestie, most Nix commands are lowkey reading these env vars the whole time πŸ‘€

Configuration environment variables

the following env vars decide how Nix loads up its configuration. if you want the full lore, it's all in the configuration file documentation.

  • NIX_CONF_DIR β€” overrides the system configuration directory.
  • NIX_USER_CONF_FILES β€” overrides the user configuration file locations.
  • NIX_CONFIG β€” provides configuration settings inline.

Store setting environment variables

  • NIX_IGNORE_SYMLINK_STORE β€” normally, the Nix store directory (typically /nix/store) isn't allowed to contain any symlink components, and that's on purpose: it's to prevent "impure" builds. here's why β€” builders sometimes "canonicalise" paths by resolving all the symlink components, so builds on different machines (where /nix/store resolves to different locations) could give you different results 😭 usually that's fine, except when builds get deployed to machines where /nix/store resolves differently. if you're 100% sure you're not gonna do that, you can set NIX_IGNORE_SYMLINK_STORE to 1.

heads up tho: if you're symlinking the Nix store just so you can put it on another file system than the root file system, on Linux you're better off using bind mount points, like:

$ 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. on Unix the default is /nix/store, set at compile time by the libstore:store-dir build option. on Windows there's no compile-time setting; the default is %PROGRAMDATA%\nix\store, determined at runtime using the %PROGRAMDATA% Known Folder.

See the Store Types chapter; each store has a store setting linking back to this as its default 🫢

  • NIX_LOG_DIR β€” overrides the location of the Nix log directory. on Unix the default is /nix/var/log/nix, set at compile time by the log-dir build option. on Windows there's no compile-time setting; the default is %PROGRAMDATA%\nix\log, determined at runtime using the %PROGRAMDATA% Known Folder.

The Local Store, Local Daemon Store, and Experimental SSH Store with filesystem mounted have per-store settings that override this.

  • NIX_STATE_DIR β€” overrides the location of the Nix state directory. on Unix the default is ${localstatedir}/nix, where localstatedir is a compile-time build option defaulting to /nix/var. on Windows there's no compile-time setting; the default is %PROGRAMDATA%\nix\state, determined at runtime using the %PROGRAMDATA% Known Folder.

The Local Store, Local Daemon Store, and Experimental SSH Store with filesystem mounted have per-store settings that override this.

  • NIX_DAEMON_SOCKET_PATH β€” overrides the path to the Unix domain socket used to communicate with the Nix daemon. it defaults to daemon-socket/socket within the state directory (see NIX_STATE_DIR).

See the Local Daemon Store documentation for the details on how the socket path is resolved ✨

  • TMPDIR β€” use the specified directory to store temporary files. this specifically includes temporary build directories, which can take up substantial amounts of disk space, so like, choose wisely 🌸 the default is /tmp.
  • NIX_REMOTE β€” overrides the store setting.

Nix language evaluator settings

  • NIX_SHOW_STATS β€” if set to 1, Nix will print some evaluation statistics, like 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 one is the moment 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 it will increase runtime because of the overhead of garbage collection. pick your trade-off bestie πŸ’€
  • NIX_PATH β€” a colon-separated list of search path entries used to resolve lookup paths.

this env var 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)

User Directories

Nix supports per-user configuration, state, and cache directories 🫢 the following env vars override the locations for these directories:

  • user configuration directory: NIX_CONFIG_HOME
  • user state directory: NIX_STATE_HOME
  • user cache directory: NIX_CACHE_HOME

when these aren't set, the defaults depend on the platform:

  • on Unix, the XDG base directories: $XDG_CONFIG_HOME/nix, $XDG_STATE_HOME/nix, $XDG_CACHE_HOME/nix
  • on Windows, the Windows Known Folders: %APPDATA%\nix\config, %LOCALAPPDATA%\nix\state, %LOCALAPPDATA%\nix\cache

for backwards compatibility, legacy Nix commands (e.g. nix-env, nix-channel) use dotfiles in $HOME instead of these directories unless use-xdg-base-directories is enabled. new Nix commands (experimental) use the proper directories by default 😌

when use-xdg-base-directories is enabled, the configuration directory is resolved as:

  1. $NIX_CONFIG_HOME, if it is defined
  2. otherwise, the platform default (e.g. $XDG_CONFIG_HOME/nix on Unix)

likewise for the state and cache directories ✨

Miscellaneous environment variables

  • IN_NIX_SHELL β€” an indicator that tells you if the current environment was set up by nix-shell. it can have the values pure or impure.

🧚 Appendix: OS-specific conventions 🧚

just so you know, this info isn't Nix-specific, but it got referenced up above πŸ‘†

Unix: XDG Base Directories

The XDG Base Directory Specification defines standard locations for user-specific configuration, state, and cache files on Unix systems.

the following env vars are used:

  • XDG_CONFIG_HOME (default ~/.config)
  • XDG_STATE_HOME (default ~/.local/state)
  • XDG_CACHE_HOME (default ~/.cache)
  • XDG_CONFIG_DIRS (default /etc/xdg) β€” colon-separated list of additional configuration base directories, searched after XDG_CONFIG_HOME

Windows: Known Folders

on Windows, Known Folders provide standard locations for application data πŸͺŸ

the relevant folders are:

  • %APPDATA% β€” per-user roaming application data
  • %LOCALAPPDATA% β€” per-user local application data
  • %PROGRAMDATA% β€” system-wide application data

πŸ’– Examples πŸ’–

Example β€” Deploy GNU Hello to an airgapped machine via USB stick πŸ“

write the closure to the block device on a machine with an 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 with no internet connection:

[bob@scratchy]$ hello=$(sudo dd if=/dev/usb | nix-store --import | tail -1)
[bob@scratchy]$ $hello/bin/hello
Hello, world!

and that's a wrap, bestie ✨ this was nix-store --export(1) β€” go forth and export your closures, you absolute icon πŸ‘‘πŸ’…

πŸ“¦ where this page comes from