Built-in FunctionsThis section lists the functions and constants built into the
Nix expression evaluator. (The built-in function
derivation is discussed above.) Some built-ins,
such as derivation, are always in scope of every
Nix expression; you can just access them right away. But to prevent
polluting the namespace too much, most built-ins are not in scope.
Instead, you can access them through the builtins
built-in value, which is a set that contains all built-in functions
and values. For instance, derivation is also
available as builtins.derivation.abortsAbort Nix expression evaluation, print error
message s.builtins.adde1e2Return the sum of the numbers
e1 and
e2.builtins.allpredlistReturn true if the function
pred returns true
for all elements of list,
and false otherwise.builtins.anypredlistReturn true if the function
pred returns true
for at least one element of list,
and false otherwise.builtins.attrNamessetReturn the names of the attributes in the set
set in a sorted list. For instance,
builtins.attrNames { y = 1; x = "foo"; }
evaluates to [ "x" "y" ].builtins.attrValuessetReturn the values of the attributes in the set
set in the order corresponding to the
sorted attribute names.baseNameOfsReturn the base name of the
string s, that is, everything following
the final slash in the string. This is similar to the GNU
basename command.builtinsThe set builtins contains all
the built-in functions and values. You can use
builtins to test for the availability of
features in the Nix installation, e.g.,
if builtins ? getEnv then builtins.getEnv "PATH" else ""
This allows a Nix expression to fall back gracefully on older Nix
installations that don’t have the desired built-in
function.builtins.compareVersionss1s2Compare 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.builtins.concatListslistsConcatenate a list of lists into a single
list.builtins.currentSystemThe built-in value currentSystem
evaluates to the Nix platform identifier for the Nix installation
on which the expression is being evaluated, such as
"i686-linux" or
"x86_64-darwin".builtins.deepSeqe1e2This is like seq
e1e2, except that
e1 is evaluated
deeply: if it’s a list or set, its elements
or attributes are also evaluated recursively.derivationattrsderivation is described in
.dirOfsReturn 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.builtins.dive1e2Return the quotient of the numbers
e1 and
e2.builtins.matchregexstrReturns a list if
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.elemxxsReturn true if a value equal to
x occurs in the list
xs, and false
otherwise.builtins.elemAtxsnReturn element n from
the list xs. Elements are counted
starting from 0. A fatal error occurs in the index is out of
bounds.builtins.fetchurlurlDownload the specified URL and return the path of
the downloaded file. This function is not available if restricted evaluation mode is
enabled.fetchTarballurlDownload 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. The top-level path component of the files
in the tarball is removed, so it is best if the tarball contains a
single directory at top level. 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-channels/archive/nixos-14.12.tar.gz) {};
stdenv.mkDerivation { … }
This function is not available if restricted evaluation mode is
enabled.builtins.filterfxsReturn a list consisting of the elements of
xs for which the function
f returns
true.builtins.filterSourcee1e2This 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).builtins.foldl’opnullistReduce 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) .... The operator is applied
strictly, i.e., its arguments are evaluated first. For example,
foldl’ (x: y: x + y) 0 [1 2 3] evaluates to
6.builtins.functionArgsf
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: ...) = { }.
builtins.fromJSONeConvert 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;
}. Floating point numbers are not
supported.builtins.genListgeneratorlengthGenerate list of size
length, with each element
i> equal to the value returned by
generatori. For
example,
builtins.genList (x: x * x) 5
returns the list [ 0 1 4 9 16 ].builtins.getAttrssetgetAttr 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.builtins.getEnvsgetEnv 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.)builtins.hasAttrssethasAttr 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.builtins.hashStringtypesReturn a base-16 representation of the
cryptographic hash of string s. The
hash algorithm specified by type must
be one of "md5", "sha1" or
"sha256".builtins.headlistReturn 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
[].importpathLoad, parse and return the Nix expression in the
file path. If path
is a directory, the file default.nix
in that directory is loaded. Evaluation aborts if the
file doesn’t exist or contains an incorrect Nix expression.
import implements Nix’s module system: you
can put any Nix expression (such as a set or a function) in a
separate file, and use it from Nix expressions in other
files.A Nix expression loaded by import must
not contain any free variables (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. For instance, if you have a calling
expression
rec {
x = 123;
y = import ./foo.nix;
}
then the following foo.nix will give an
error:
x + 456
since x is not in scope in
foo.nix. If you want x
to be available in foo.nix, you should pass
it as a function argument:
rec {
x = 123;
y = import ./foo.nix x;
}
and
x: x + 456
(The function argument doesn’t have to be called
x in foo.nix; any name
would work.)builtins.intersectAttrse1e2Return a set consisting of the attributes in the
set e2 that also exist in the set
e1.builtins.isAttrseReturn true if
e evaluates to a set, and
false otherwise.builtins.isListeReturn true if
e evaluates to a list, and
false otherwise.builtins.isFunctioneReturn true if
e evaluates to a function, and
false otherwise.builtins.isStringeReturn true if
e evaluates to a string, and
false otherwise.builtins.isInteReturn true if
e evaluates to an int, and
false otherwise.builtins.isBooleReturn true if
e evaluates to a bool, and
false otherwise.isNulleReturn true if
e evaluates to null,
and false otherwise.This function is deprecated;
just write e == null instead.builtins.lengtheReturn the length of the list
e.builtins.lessThane1e2Return 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.builtins.listToAttrseConstruct 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.
Example:
builtins.listToAttrs
[ { name = "foo"; value = 123; }
{ name = "bar"; value = 456; }
]
evaluates to
{ foo = 123; bar = 456; }
mapflistApply the function f to
each element in the list list. For
example,
map (x: "foo" + x) [ "bar" "bla" "abc" ]
evaluates to [ "foobar" "foobla" "fooabc"
].builtins.mule1e2Return the product of the numbers
e1 and
e2.builtins.parseDrvNamesSplit the string s into
a package name and version. The package name is everything up to
but not including the first dash followed by a digit, 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";
}.builtins.pathExistspathReturn true if the path
path exists, and
false otherwise. One application of this
function is to conditionally include a Nix expression containing
user configuration:
let
fileName = builtins.getEnv "CONFIG_FILE";
config =
if fileName != "" && builtins.pathExists (builtins.toPath fileName)
then import (builtins.toPath fileName)
else { someSetting = false; }; # default configuration
in config.someSetting
(Note that CONFIG_FILE must be an absolute path for
this to work.)builtins.readDirpathReturn 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".builtins.readFilepathReturn the contents of the file
path as a string.removeAttrssetlistRemove 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; }.builtins.replaceStringsfromtosGiven string s, replace
every occurrence of the strings in from
with the corresponding string in
to. For example,
builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"
evaluates to "fabir".builtins.seqe1e2Evaluate e1, then
evaluate and return e2. This ensures
that a computation is strict in the value of
e1.builtins.sortcomparatorlistReturn 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.builtins.stringLengtheReturn the length of the string
e. If e is
not a string, evaluation is aborted.builtins.sube1e2Return the difference between the numbers
e1 and
e2.builtins.substringstartlensReturn the substring of
s from character 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, and if start +
len lies beyond the end of the string, 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".
builtins.taillistReturn the second to last elements of a list;
abort evaluation if the argument isn’t a list or is an empty
list.throwsThrow 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).builtins.toFilenamesStore 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
and 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://nix.cs.uu.nl/dist/tarballs/hello-2.1.1.tar.gz;
md5 = "70c9ccf9fac07f762c24f2df2290784d";
};
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 an antiquotation
(see ), 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.builtins.toJSONeReturn 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.builtins.toPathsConvert the string value
s into a path value. The string
s must represent an absolute path
(i.e., must start with /). The path need not
exist. The resulting path is canonicalised, e.g.,
builtins.toPath "//foo/xyzzy/../bar/" returns
/foo/bar.toStringeConvert 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: ...; }.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.builtins.toXMLeReturn 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. shows an example where this is
the case. 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 () is applied to it () to
generate the XML configuration file for the Jetty server. The XML
representation produced from by toXML is shown in .Note that uses 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 at
xsltproc ${stylesheet}
....Passing information to a builder
using toXML $out/server-conf.xml]]>
";
servlets = builtins.toXML []]> XML representation produced by
toXML]]>builtins.tracee1e2Evaluate e1 and print its
abstract syntax representation on standard error. Then return
e2. This function is useful for
debugging.builtins.tryEvaleTry to 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.
builtins.typeOfeReturn a string representing the type of the value
e, namely "int",
"bool", "string",
"path", "null",
"set", "list" or
"lambda".