Nix{,OS,pkgs} bag of tricks
Last updated at 2023-06-23.
This is my personal collection of somewhat unknown, but occasionally useful, features of the Nix ecosystem, in no particular order.
Nix language
__curPos
evaluates to an attrset containing the current file and line/column. It is handled directly in the parser.builtins.unsafeGetAttrPos name attrset
returns position information for a specified attribute in an attrset. Both of these should be used with care, as the same expression at a different position will return different values.
Nixpkgs
- Setting the NIX_DEBUG environment variable in a derivation enables extra logging output during the build. Setting it to 6 or higher enables
set -x
:nix-build -E '(import <nixpkgs> {}).hello.overrideAttrs (_: { NIX_DEBUG = 6; })'
- The module system that backs NixOS can be used standalone, without any predefined modules. This is also how the Nixpkgs's
config
is implemented:nix-repl> x = lib.evalModules { modules = [{ options.foo = lib.mkOption { type = lib.types.str; }; } { foo = "bar"; } ]; } nix-repl> x.config.foo "bar"
- If you have a
callPackage
-style out-of-tree package, you can build it with the scriptmaintainers/scripts/nix-call-package
from the nixpkgs source tree. Note: This script will build your package by importing<nixpkgs>
, and not by importing the source tree in which the script is stored!$ cat foo.nix { runCommand }: runCommand "foo" {} "echo hello world > $out" $ ~/src/nixpkgs/maintainers/scripts/nix-call-package ./foo.nix warning: you did not specify '--add-root'; the result might be removed by the garbage collector warning: you did not specify '--add-root'; the result might be removed by the garbage collector /nix/store/gnr862zavclmh273w4h1h6v78b6jaix3-foo
nix-shell -p
, without any further arguments, is a quick and dirty way to get into a development shell with a properly configured C compiler etc. available.
NixOS
- /etc/hosts management:
networking.hosts
lets you add to your hosts fileenvironment.etc.hosts.mode = "0644";
makes your hosts file writable
systemd.tmpfiles.rules
lets you declaratively create file system structures (e.g. directories, symlinks, etc.). Adding a rule without an expiration date removes the "temporary" aspect of tmpfiles.