NIX-STORE-GC(1)

✨ nix-store --gc(1) β€” garbage collection, bestie edition ✨

okay so this is the nix-store --gc page from the General Commands Manual, and it's literally about running garbage collection. it's giving spring cleaning but for your Nix store πŸ§ΉπŸ’–

🌸 Name 🌸

nix-store --gc β€” run garbage collection


πŸŽ€ Synopsis πŸŽ€

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

πŸ¦‹ Description πŸ¦‹

so if you run --gc with no extra flags, it does a whole garbage collection on the Nix store. translation: every path in the Nix store that is not reachable via file system references from a set of "roots" gets yeeted. gone. deleted. bye πŸ’€

here are the suboperations you can pick from:

  • --print-roots β€” this one prints the set of roots that the garbage collector uses, straight to standard output. no deleting, just showing you the receipts πŸ‘€
  • --print-live β€” prints the set of "live" store paths to standard output. live paths = all the store paths reachable from the roots. and bestie, live paths should never be deleted, because that would break consistency β€” it would become possible that applications are installed that reference things that are no longer present in the store. imagine referencing something that doesn't exist anymore… the audacity 😭
  • --print-dead β€” prints the set of "dead" store paths to standard output, which is literally just the opposite of the live set: any path in the store that is not live (with respect to the roots) is dead. periodt.

by default, all unreachable paths get 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 bytes argument can be followed by a multiplicative suffix K, M, G or T, denoting KiB, MiB, GiB or TiB units. so like, --max-freed 2G is a whole vibe ✨

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

and by default, the collector prints the total number of freed bytes when it finishes (or when it is interrupted). so you always know how much you cleaned up 🫢


πŸ’… OPTIONS πŸ’…

the following options are allowed for all nix-store operations, but may not always have an effect. (yes, they show up for the vibes even when they do nothing πŸ™ˆ)

  • --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. iconic behaviour, honestly 🌈

⚠️ 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. so don't try it, bestie πŸ’€

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). queen of organization πŸ‘‘


more parts coming, don't go anywhere 🫢

πŸ’… Common Options πŸ’…

ok bestie, so most Nix commands all speak the same lil language of flags 🫢 like it's giving shared group chat, and here's the whole roster of command-line options they accept:

  • --help β€” spits out a summary of the command syntax and then dips. that's it, that's the whole job ✨
  • --version β€” prints the Nix version number on standard output and exits. short, sweet, iconic πŸ‘‘
  • --verbose, -v β€” turns the volume UP on diagnostic messages printed on standard error. lowkey important: for every Nix operation, what lands on standard output is well-defined, and any diagnostics go to standard error, never standard output. you can stack this option multiple times, and rn these are the verbosity levels that exist:
    • 0 β€œErrors only” β€” only prints messages explaining why the Nix invocation failed. the bare minimum fr πŸ’€
    • 1 β€œInformational” β€” prints useful messages about what Nix is doing. this is the default πŸ“
    • 2 β€œTalkative” β€” more informational messages. it's yapping now πŸ—£οΈ
    • 3 β€œChatty” β€” even more of them. full yap mode activated ✨
    • 4 β€œDebug” β€” debug information. we're in the weeds bestie πŸ”
    • 5 β€œVomit” β€” vast amounts of debug information. the name is not a metaphor, it's a lifestyle 😭
  • --quiet β€” turns the volume DOWN on diagnostic messages printed on standard error. it's the inverse option to -v / --verbose. also stackable multiple times, and yeah, same verbosity level list as above πŸŽ€
  • *--log-format *format β€” switches up how the log output looks, 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 like, don't hardcode your feelings onto it πŸ™ˆ
  • bar β€” only displays a progress bar during the builds. aesthetic, minimal, slay 🌈
  • bar-with-logs β€” displays the raw logs, with the progress bar vibing at the bottom.
  • --no-build-output, -Q β€” by default, whatever the builders write to standard output and standard error gets echoed to the Nix command's standard error. this option suppresses that behaviour. but bestie, heads up: 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 max number of build jobs Nix will run in parallel to number. pass auto and it'll use however many CPUs the system has. the default comes from the max-jobs configuration setting, which itself defaults to 1. a higher value hits on SMP systems or when you're exploiting I/O latency. setting it to 0 disallows building on the local machine, which is exactly what you want when you only want builds happening on remote builders πŸ‘‘
  • --cores β€” sets the value of the NIX_BUILD_CORES environment variable in the invocation of builders. builders can use that variable at their own discretion to control max 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. and the value 0 means the builder should use all available CPU cores in the system πŸ”₯
  • --max-silent-time β€” sets the max number of seconds a builder can go without producing any data on standard output or standard error. default comes from the max-silent-time configuration setting. 0 means no time-out 🀐
  • --timeout β€” sets the max number of seconds a builder can run. default comes from the timeout configuration setting. 0 means no timeout ⏰
  • --keep-going, -k β€” keeps going in case of failed builds, to the greatest extent possible. like, if building an input of some derivation fails, Nix will still build the other inputs, just not the derivation itself. without this option, Nix stops if any build fails (except for builds of substitutes), possibly killing builds in progress when we're in parallel or distributed build territory πŸ’€
  • --keep-failed, -K β€” says that in case of a build failure, the temporary directory where the build took place (usually in /tmp) should not be deleted. the path of the build directory gets printed as an informational message, so go look at it bestie πŸ”
  • --fallback β€” whenever Nix tries to build a derivation for which substitutes are known for each output path, but realising those output paths through the substitutes fails, it falls back on building the derivation.

the most common scenario where this hits is when we've got registered substitutes for binary distribution from, say, a network repository. if the repo is down, realising the derivation fails. with this option, Nix builds the derivation instead. so installation from binaries falls back on installation from source 🫢 this is not the default, because generally you don't want a transient failure in obtaining substitutes to lead to a whole build from source (and all the resource munching that comes with it).

  • --readonly-mode β€” when this one's on, no attempt is made to open the Nix database. most Nix operations do need database access, so those operations will just fail πŸ’€
  • *--arg *name value β€” accepted by nix-env, nix-instantiate, nix-shell and nix-build. when evaluating Nix expressions, the expression evaluator automatically tries 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 the value you gave it πŸ’…

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 it with --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 β€” 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 β€” this one's like --arg, only the value isn't a Nix expression, it's a string. so instead of --arg system \"i686-linux\" (the outer quotes are there to keep the shell happy), you can just say --argstr system i686-linux ✨
  • *--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. peep nix-env --install for some concrete examples πŸ‘€

besides attribute names, you can also specify array indices. like, 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. yes, fourth, because indices start at zero, we don't make the rules 🫠

  • *--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 β€” interprets 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 a shell that contains the built packages ready for use, give your expression to the nix-shell --packages convenience flag instead πŸ’…

  • *-I, --include *path β€” adds an entry to the list of search paths used to resolve lookup paths. can be given multiple times ✨

paths added through -I take precedence over the nix-path configuration setting and the NIX_PATH environment variable. so like, -I is the main character here πŸ‘‘

  • --impure β€” allows access to mutable paths and repositories 🌈
  • *--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. 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 ✨

okay so bestie, most Nix commands interpret the following environment variables β€” think of them as the little settings gremlins that change how Nix behaves. πŸ’–

βš™οΈ Configuration environment variables

The following environment variables affect how Nix loads its configuration. See the configuration file documentation for full details. πŸ“š

  • 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) 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. On Unix, the default is /nix/store, set at compile time by the libstore:store-dir build option. On Windows, there is 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 is 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 is 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. Defaults to daemon-socket/socket within the state directory (see NIX_STATE_DIR).

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

  • 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 β€” Overrides the store setting.

🧠 Nix language evaluator settings

  • 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.
  • 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)

🏠 User Directories

Nix supports per-user configuration, state, and cache directories. The following environment variables override the locations for these directories:

  • user configuration directory ([user configuration directory]{#user-conf-dir}): NIX_CONFIG_HOME ([NIX_CONFIG_HOME]{#env-NIXCONFIGHOME})
  • user state directory: NIX_STATE_HOME ([NIX_STATE_HOME]{#env-NIXSTATEHOME})
  • user cache directory: NIX_CACHE_HOME ([NIX_CACHE_HOME]{#env-NIXCACHEHOME})

When these are not 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 β€” Indicator that tells if the current environment was set up by nix-shell. It can have the values pure or impure.

πŸ“Ž Appendix: OS-specific conventions

This information is not Nix-specific, but is referenced 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 environment variables are used:

  • [XDG_CONFIG_HOME]{#env-XDGCONFIGHOME} (default ~/.config)
  • [XDG_STATE_HOME]{#env-XDGSTATEHOME} (default ~/.local/state)
  • [XDG_CACHE_HOME]{#env-XDGCACHEHOME} (default ~/.cache)
  • [XDG_CONFIG_DIRS]{#env-XDGCONFIGDIRS} (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 on Windows.

The relevant folders are:

  • [%APPDATA%]{#env-APPDATA} β€” per-user roaming application data
  • [%LOCALAPPDATA%]{#env-LOCALAPPDATA} β€” per-user local application data
  • [%PROGRAMDATA%]{#env-PROGRAMDATA} β€” system-wide application data

πŸŽ€ 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))

That’s the whole manual, bestie! Footer tea: this is nix-store --gc(1) β€” source/version and date live on the last line of the real page. Stay iconic πŸ’…βœ¨

πŸ“¦ where this page comes from