This book is available online and as a downloadable PDF.
Acknowledgments
I would like to thank the patient people on the NixOS Discourse Forum who answered my many questions, especially cdepillabout, FedericoSchonborn, tejing and smkuehnhold. Any mistakes in this book are my own, however.
1. Introduction
1.1. Why Nix?
If you’ve opened this PDF, you already have your own motivation for learning Nix. Here’s how it helps me. As a researcher, I tend to work on a series of short-term projects, mostly demos and prototypes...
This book is available online and as a downloadable PDF.
Acknowledgments
I would like to thank the patient people on the NixOS Discourse Forum who answered my many questions, especially cdepillabout, FedericoSchonborn, tejing and smkuehnhold. Any mistakes in this book are my own, however.
1. Introduction
1.1. Why Nix?
If you’ve opened this PDF, you already have your own motivation for learning Nix. Here’s how it helps me. As a researcher, I tend to work on a series of short-term projects, mostly demos and prototypes. For each one, I typically develop some software using a compiler, often with some open source libraries. Often I use other tools to analyse data or generate documentation, for example.
Problems would arise when handing off the project to colleagues; they would report errors when trying to build or run the project. Belatedly I would realise that my code relies on a library that they need to install. Or perhaps they had installed the library, but the version they’re using is incompatible.
Using containers helped with the problem. However, I didn’t want to develop in a container. I did all my development in my nice, familiar, environment with my custom aliases and shell prompt. and then I containerised the software. This added step was annoying for me, and if my colleague wanted to do some additional development, they would probably extract all of the source code from the container first anyway. Containers are great, but this isn’t the ideal use case for them.
Nix allows me to work in my custom environment, but forces me to specify any dependencies. It automatically tracks the version of each dependency so that it can replicate the environment wherever and whenever it’s needed.
1.2. Why flakes?
Flakes are labeled as an experimental feature, so it might seem safer to avoid them. However, they have been in use for years, and there is widespread adoption, so the aren’t going away any time soon. Flakes are easier to understand, and offer more features than the traditional Nix approach. After weighing the pros and cons, I feel it’s better to learn and use flakes; and this seems to be the general consensus.
1.3. Prerequisites
To follow along with the examples in this book, you will need access to a computer or (virtual machine) with Nix (or NixOS) installed and flakes enabled.
I recommend the installer from zero-to-nix.com. This installer automatically enables flakes.
More documentation (and another installer) available at nixos.org.
To enable flakes on an existing Nix or NixOS installation, see the instructions in the NixOS wiki.
| ** | There are hyphenated and un-hyphenated versions of many Nix commands. For example, nix-shell and nix shell are two different commands. Don’t confuse them! Generally speaking, the un-hyphenated versions are for working directly with flakes, while the hyphenated versions are for everything else. |
1.4. See an error? Have a suggestion? Or want more?
If notice an error in this book, have a suggestion on how to improve it, or you’re interested in an area that isn’t covered, feel free to open an issue.
2. The Nix language
2.1. Introducing the Nix language
Nix and NixOS use a functional programming language called Nix to specify how to build and install software, and how to configure system, user, and project-specific environments. (Yes, “Nix” is the name of both the package manager and the language it uses.)
Nix is a functional language. In a procedural language such as C or Java, the focus is on writing a series of steps (statements) to achieve a desired result. By contrast, in a functional language the focus is on defining the desired result.
In the case of Nix, the desired result is usually a derivation: a software package that has been built and made available for use. The Nix language has been designed for that purpose, and thus has some features you don’t typically find in general-purpose languages.
2.2. Data types
2.2.1. Strings
Strings are enclosed by double quotes ("), or two single quotes (').
"Hello, world!"
''This string contains "double quotes"''
They can span multiple lines.
''Old pond
A frog jumps in
The sound of water
-- Basho''
2.2.2. Integers
7
256
2.2.3. Floating point numbers
3.14
6.022e23
2.2.4. Boolean
The Boolean values in Nix are true and false.
2.2.5. Paths
File paths play an important role in building software, so Nix has a special data type for them. Paths may be absolute (e.g. /bin/sh) or relative (e.g. ./data/file1.csv). Note that paths are not enclosed in quotation marks; they are not strings!
Enclosing a path in angle brackets, e.g. <nixpkgs> causes the directories listed in the environment variable NIX_PATH to be searched for the given file or directory name. These are called lookup paths.
2.2.6. Lists
List elements are enclosed in square brackets and separated by spaces (not commas). The elements need not be of the same type.
[ "apple" 123 ./build.sh false ]
Lists can be empty.
[]
List elements can be of any type, and can even be lists themselves.
[ [ 1 2 ] [ 3 4 ] ]
2.2.7. Attribute sets
Attribute sets associate keys with values. They are enclosed in curly brackets, and the associations are terminated by semi-colons. Note that the final semi-colon before the closing bracket is required.
{ name = "Professor Paws"; age = 10; species = "cat"; }
The keys of an attribute set must be strings. When the key is not a valid identifier, it must be enclosed in quotation marks.
{ abc = true; "123" = false; }
Attribute sets can be empty.
{}
Values of attribute sets can be of any type, and can even be attribute sets themselves.
{ name = { first = "Professor"; last = "Paws"; }; age = 10; species = "cat"; }
In Section 2.11.4, “Recursive attribute sets” you will be introduced to a special type of attribute set.
| ** | In some Nix documentation, and in many articles about Nix, attribute sets are simply called “sets”. |
2.2.8. Functions
We’ll learn how to write functions later in this chapter. For now, note that functions are “first-class values”, meaning that they can be treated like any other data type. For example, a function can be assigned to a variable, appear as an element in a list, or be associated with a key in an attribute set.
[ "apple" 123 ./build.sh false (x: x*x) ]
{ name = "Professor Paws"; age = 10; species = "cat"; formula = (x: x*2); }
2.3. Stop reading this chapter!
When I first began using Nix, it seemed logical to start by learning the Nix language. However, after following an in-depth tutorial, I found that I didn’t know how to do anything useful with the language! It wasn’t until later that I understood what I was missing: a guide to the most useful library functions.
When working with Nix or NixOS, it’s very rare that you’ll want to write something from scratch. Instead, you’ll use one of the many library functions that make things easier and shield you from the underlying complexity. Many of these functions are language-specific, and the documentation for them may be inadequate. Often the easiest (or only) way to learn to use them is to find an example that does something similar to what you want, and then modify the function parameters to suit your needs.
At this point you’ve learned enough of the Nix language to do the majority of common Nix tasks. So when I say “Stop reading this chapter!”, I’m only half-joking. Instead I suggest that you skim the rest of this chapter, paying special attention to anything marked with **. Then move on to the following chapters where you will learn how to develop and package software using Nix. Afterward, come back to this chapter and read it in more detail.
While writing this book, I anticipated that readers would want to skip around, alternating between pure learning and learning-by-doing. I’ve tried to structure the book to support that; sometimes repeating information from earlier chapters that you might have skipped.
2.4. The Nix REPL
The Nix REPL [1] is an interactive environment for evaluating and debugging Nix code. It’s also a good place to begin learning Nix. Enter it using the command nix repl. Within the REPL, type :? to see a list of available commands.
$ nix repl
Welcome to Nix 2.18.1. Type :? for help.
nix-repl> :?
The following commands are available:
<expr> Evaluate and print expression
<x> = <expr> Bind expression to variable
:a, :add <expr> Add attributes from resulting set to scope
:b <expr> Build a derivation
:bl <expr> Build a derivation, creating GC roots in the
working directory
:e, :edit <expr> Open package or function in $EDITOR
:i <expr> Build derivation, then install result into
current profile
:l, :load <path> Load Nix expression and add it to scope
:lf, :load-flake <ref> Load Nix flake and add it to scope
:p, :print <expr> Evaluate and print expression recursively
:q, :quit Exit nix-repl
:r, :reload Reload all files
:sh <expr> Build dependencies of derivation, then start
nix-shell
:t <expr> Describe result of evaluation
:u <expr> Build derivation, then start nix-shell
:doc <expr> Show documentation of a builtin function
:log <expr> Show logs for a derivation
:te, :trace-enable [bool] Enable, disable or toggle showing traces for
errors
:?, :help Brings up this help menu
A command that is useful to beginners is :t, which tells you the type of an expression.
Note that the command to exit the REPL is :q (or :quit if you prefer).
2.5. Variables
2.5.1. Assignment
You can declare variables in Nix and assign values to them.
nix-repl> a = 7
nix-repl> b = 3
nix-repl> a - b
4
| ** | The spaces before and after operators aren’t always required. However, you can get unexpected results when you omit them, as shown in the following example. Nix allows hyphens (-) in variable names, so a-b is interpreted as the name of a variable rather than a subtraction operation. |
nix-repl> a-b
error: undefined variable 'a-b'
at «string»:1:1:
1| a-b
| ^
``` |
#### 2\.5\.2\. Immutability
In Nix, values are *immutable*; once you assign a value to a variable, you cannot change it\. You can, however, create a new variable with the same name, but in a different scope\. Don’t worry if you don’t completely understand the previous sentence; we will see some examples in [\[\_functions\]](#_functions), [Section 2\.15, “Let expressions”](#_let_expressions), and [Section 2\.16, “With expressions”](#_with_expressions)\.
| | |
| - | - |
| ** | In the Nix REPL, it may seem like the values of variables can be changed, in *apparent* contradiction to the previous paragraph\. In truth, the REPL works some behind-the-scenes "magic", effectively creating a new nested scope with each assignment\. This makes it much easier to experiment in the REPL\.
nix-repl> x = 1
nix-repl> x 1
nix-repl> x = x + 1 # creates a new variable called “x”; the original is no longer in scope
nix-repl> x 2
### 2\.6\. Numeric operations
#### 2\.6\.1\. Arithmetic operators
The usual arithmetic operators are provided\.
nix-repl> 1 + 2 # addition 3
nix-repl> 5 - 3 # subtraction 2
nix-repl> 3 * 4 # multiplication 12
nix-repl> 6 / 2 # division 3
nix-repl> -1 # negation -1
| | |
| - | - |
| ** | As mentioned in [Section 2\.5, “Variables”](#_variables), you can get unexpected results when you omit spaces around operators\. Consider the following example\.
nix-repl> 6/2 /home/amy/codeberg/nix-book/6/2
What happened? Let’s use the `:t` command to find out the type of the expression\.
nix-repl> :t 6/2 a path
If an expression can be interpreted as a path, Nix will do so\. This is useful, because paths are *far* more commonly used in Nix expressions than arithmetic operators\. In this case, Nix interpreted `6/2` as a relative path from the current directory, which in the above example was `/home/amy/codeberg/nix-book`\. Adding a space after the `/` operator produces the expected result\.
nix-repl> 6/ 2 3
To avoid surprises and improve readability, I prefer to use spaces before and after all operators\. |
#### 2\.6\.2\. Floating-point calculations
Numbers without a decimal point are assumed to be integers\. To ensure that a number is interpreted as a floating-point value, add a decimal point\.
nix-repl> :t 5 an integer
nix-repl> :t 5.0 a float
nix-repl> :t 5. a float
In the example below, the first expression results in integer division \(rounding down\), while the second produces a floating-point result\.
nix-repl> 5 / 3 1
nix-repl> 5.0 / 3 1.66667
### 2\.7\. String operations
#### 2\.7\.1\. String concatenation
String concatenation uses the `+` operator\.
nix-repl> “Hello, “ + “world!” “Hello, world!”
#### 2\.7\.2\. String interpolation
You can use the `${*variable*}` syntax to insert the value of a variable within a string\.
nix-repl> name = “Wombat”
nix-repl> “Hi, I’m ${name}.” “Hi, I’m Wombat.”
| | |
| - | - |
| ** | You cannot mix numbers and strings\. Earlier we set `a = 7`, so the following expression fails\.
nix-repl> “My favourite number is ${a}.” error: … while evaluating a path segment
at «string»:1:25:
1| “My favourite number is ${a}.” | ^
error: cannot coerce an integer to a string
Nix does provide functions for converting between types; we’ll see these in the [next section](#convert-to-string)\. |
#### 2\.7\.3\. Useful built-in functions for strings
Nix provides some built-in functions for working with strings; a few examples are shown below\. For more information on these and other built-in functions, see the Nix Manual \([https://nixos\.org/manual/nix/stable/language/builtins](https://nixos.org/manual/nix/stable/language/builtins)\)\.
How long is this string?
nix-repl> builtins.stringLength “supercalifragilisticexpialidocious” 34
Given a starting position and a length, extract a substring\. The first character of a string has index `0`\.
nix-repl> builtins.substring 3 6 “hayneedlestack” “needle”
Convert an expression to a string\.
nix-repl> builtins.toString 7 “7”
nix-repl> builtins.toString (3*4 + 1) “13”
### 2\.8\. Boolean operations
The usual boolean operators are available\. Recall that earlier we set `a = 7` and `b = 3`\.
nix-repl> a == 7 # equality test true
nix-repl> b != 3 # inequality false
nix-repl> a > 12 # greater than false
nix-repl> b >= 2 # greater than or equal true
nix-repl> a < b # less than false
nix-repl> b <= a # less than or equal true
nix-repl> !true # logical negation false
nix-repl> (3 * a == 21) && (a > b) # logical AND true
nix-repl> (b > a) || (b > 10) # logical OR false
One operator that might be unfamiliar to you is *logical implication*, which uses the symbol `→`\. The expression `u → v` is equivalent to `!u || v`\.
nix-repl> u = false
nix-repl> v = true
nix-repl> u -> v true
nix-repl> v -> u false
### 2\.9\. Path operations
Any expression that contains a forward slash \(`/`\) *not* followed by a space is interpreted as a path\. To refer to a file or directory relative to the current directory, prefix it with `./`\. You can specify the current directory as `./.`
nix-repl> ./file.txt /home/amy/codeberg/nix-book/file.txt
nix-repl> ./. /home/amy/codeberg/nix-book
#### 2\.9\.1\. Concatenating paths
Paths can be concatenated to produce a new path\.
nix-repl> /home/wombat + /bin/sh /home/wombat/bin/sh
nix-repl> :t /home/wombat + /bin/sh a path
| | |
| - | - |
| ** | Relative paths are made absolute when they are parsed, which occurs before concatenation\. This is why the result in the example below is not `/home/wombat/file.txt`\.
nix-repl> /home/wombat + ./file.txt /home/wombat/home/amy/codeberg/nix-book/file.txt
#### 2\.9\.2\. Concatenating a path \+ a string
A path can be concatenated with a string to produce a new path\.
nix-repl> /home/wombat + “/file.txt” /home/wombat/file.txt
nix-repl> :t /home/wombat + “/file.txt” a path
#### 2\.9\.3\. Concatenating a string \+ a path
Strings can be concatenated with paths, but with a side-effect that may surprise you: if the path exists, the file is copied to the Nix store\! The result is a string, not a path\.
In the example below, the file `file.txt` is copied to `/nix/store/gp8ba25gpwvbqizqfr58jr014gmv1hd8-file.txt` \(not, as you might expect, to `/home/wombat/nix/store/gp8ba25gpwvbqizqfr58jr014gmv1hd8-file.txt`\)\.
nix-repl> “/home/wombat” + ./file.txt “/home/wombat/nix/store/gp8ba25gpwvbqizqfr58jr014gmv1hd8-file.txt”
The path must exist\.
nix-repl> “/home/wombat” + ./no-such-file.txt error (ignored): error: end of string reached error: getting status of ‘/home/amy/codeberg/nix-book/no-such-file.txt’: No such file or directory
#### 2\.9\.4\. Useful built-in functions for paths
Nix provides some built-in functions for working with paths; a few examples are shown below\. For more information on these and other built-in functions, see the Nix Manual \([https://nixos\.org/manual/nix/stable/language/builtins](https://nixos.org/manual/nix/stable/language/builtins)\)\.
Does the path exist?
nix-repl> builtins.pathExists ./index.html true
nix-repl> builtins.pathExists /no/such/path false
Get a list of the files in a directory, along with the type of each file\.
nix-repl> builtins.readDir ./. { “.envrc” = “regular”; “.git” = “directory”; “.gitignore” = “regular”; Makefile = “regular”; images = “directory”; “index.html” = “regular”; “shell.nix” = “regular”; source = “directory”; themes = “directory”; “wombats-book-of-nix.pdf” = “regular”; }
Read the contents of a file into a string\.
nix-repl> builtins.readFile ./.envrc “use nix\n”
### 2\.10\. List operations
#### 2\.10\.1\. List concatenation
Lists can be concatenated using the `++` operator\.
nix-repl> [ 1 2 3 ] ++ [ “apple” “banana” ] [ 1 2 3 “apple” “banana” ]
#### 2\.10\.2\. Useful built-in functions for lists
Nix provides some built-in functions for working with lists; a few examples are shown below\. For more information on these and other built-in functions, see the Nix Manual \([https://nixos\.org/manual/nix/stable/language/builtins](https://nixos.org/manual/nix/stable/language/builtins)\)\.
Testing if an element appears in a list\.
nix-repl> fruit = [ “apple” “banana” “cantaloupe” ]
nix-repl> builtins.elem “apple” fruit true
nix-repl> builtins.elem “broccoli” fruit false
Selecting an item from a list by index\. The first element in a list has index `0`\.
nix-repl> builtins.elemAt fruit 0 “apple”
nix-repl> builtins.elemAt fruit 2 “cantaloupe”
Determining the number of elements in a list\.
nix-repl> builtins.length fruit 3
Accessing the first element of a list\.
nix-repl> builtins.head fruit “apple”
Dropping the first element of a list\.
nix-repl> builtins.tail fruit [ “banana” “cantaloupe” ]
Functions are useful for working with lists\. Functions will be introduced in [Section 2\.12, “Functions”](#functions), but the following examples should be somewhat self-explanatory\.
Using a function to filter \(select elements from\) a list\.
nix-repl> numbers = [ 1 3 6 8 9 15 25 ]
nix-repl> isBig = n: n > 10 # is the number “big” (greater than 10)?
nix-repl> builtins.filter isBig numbers # get just the “big” numbers [ 15 25 ]
Applying a function to all the elements in a list\.
nix-repl> double = n: 2*n # multiply by two
nix-repl> builtins.map double numbers # double each element in the list [ 2 6 12 16 18 30 50 ]
### 2\.11\. Attribute set operations
#### 2\.11\.1\. Selection
The `.` operator selects an attribute from a set\.
nix-repl> animal = { name = { first = “Professor”; last = “Paws”; }; age = 10; species = “cat”; }
nix-repl> animal . age 10
nix-repl> animal . name . first “Professor”
#### 2\.11\.2\. Query
We can use the `?` operator to find out if a set has a particular attribute\.
nix-repl> animal ? species true
nix-repl> animal ? bicycle false
#### 2\.11\.3\. Modification
We can use the `//` operator to modify an attribute set\. Recall that Nix values are immutable, so the result is a new value \(the original is not modified\)\. Attributes in the right-hand set take preference\.
nix-repl> animal // { species = “tiger”; } { age = 10; name = { … }; species = “tiger”; }
#### 2\.11\.4\. Recursive attribute sets
An ordinary attribute set cannot refer to its own elements\. To do this, you need a *recursive* attribute set\.
nix-repl> { x = 3; y = 4*x; } error: undefined variable ‘x’
at «string»:1:16:
1| { x = 3; y = 4*x; } | ^
nix-repl> rec { x = 3; y = 4*x; } { x = 3; y = 12; }
#### 2\.11\.5\. Useful built-in functions for attribute sets
Nix provides some built-in functions for working with attribute sets; a few examples are shown below\. For more information on these and other built-in functions, see the Nix Manual \([https://nixos\.org/manual/nix/stable/language/builtins](https://nixos.org/manual/nix/stable/language/builtins)\)\.
Get an alphabetical list of the keys\.
nix-repl> builtins.attrNames animal [ “age” “name” “species” ]
Get the values associated with each key, in alphabetical order by the key names\.
nix-repl> builtins.attrValues animal [ 10 “Professor Paws” “cat” ]
What value is associated with a key?
nix-repl> builtins.getAttr “age” animal 10
Does the set have a value for a key?
nix-repl> builtins.hasAttr “name” animal true
nix-repl> builtins.hasAttr “car” animal false
Remove one or more keys and associated values from a set\.
nix-repl> builtins.removeAttrs animal [ “age” “species” ] { name = “Professor Paws”; }
### 2\.12\. Functions
#### 2\.12\.1\. Anonymous functions
Functions are defined using the syntax `*parameter*: *expression*`, where the *expression* typically involves the *parameter*\. Consider the following example\.
nix-repl> x: x + 1 «lambda @ «string»:1:1»
We created a function that adds `1` to its input\. However, it doesn’t have a name, so we can’t use it directly\. Anonymous functions do have their uses, as we shall see shortly\.
Note that the message printed by the Nix REPL when we created the function uses the term *lambda*\. This derives from a branch of mathematics called *lambda calculus*\. Lambda calculus was the inspiration for most functional languages such as Nix\. Functional programmers often call anonymous functions "lambdas"\.
The Nix REPL confirms that the expression `x: x + 1` defines a function\.
nix-repl> :t x: x + 1 a function
#### 2\.12\.2\. Named functions and function application
How can we use a function? Recall from [Section 2\.2\.8, “Functions”](#type-lambda) that functions can be treated like any other data type\. In particular, we can assign it to a variable\.
nix-repl> f = x: x + 1
nix-repl> f «lambda @ «string»:1:2»
Procedural languages such as C or Java often use parenthesis to apply a function to a value, e\.g\. `f(5)`\. Nix, like lambda calculus and most functional languages, does not require parenthesis for function application\. This reduces visual clutter when chaining a series of functions\.
Now that our function has a name, we can use it\.
nix-repl> f 5 6
#### 2\.12\.3\. Multiple parameters using nested functions
Functions in Nix always have a single parameter\. To define a calculation that requires more than one parameter, we create functions that return functions\!
nix-repl> add = a: (b: a+b)
We have created a function called `add`\. When applied to a parameter `a`, it returns a new function that adds `a` to its input\. Note that the expression `(b: a+b)` is an anonymous function\. We never call it directly, so it doesn’t need a name\. Anonymous functions are useful after all\!
I used parentheses to emphasise the inner function, but they aren’t necessary\. More commonly we would write the following\.
nix-repl> add = a: b: a+b
If we only supply one parameter to `add`, the result is a new function rather than a simple value\. Invoking a function without supplying all of the expected parameters is called *partial application*\.
nix-repl> add 3 # Returns a function that adds 3 to any input «lambda @ «string»:1:6»
Now let’s apply `add 3` to the value `5`\.
nix-repl> (add 3) 5 8
In fact, the parentheses aren’t needed\.
nix-repl> add 3 5 8
If you’ve never used a functional programming language, this all probably seems very strange\. Imagine that you want to add two numbers, but you have a very unusual calculator labeled "add"\. This calculator never displays a result, it only produces more calculators\! If you enter the value `3` into the "add" calculator, it gives you a second calculator labeled "add 3"\. You then enter `5` into the "add 3" calculator, which displays the result of the addition, `8`\.
With that image in mind, let’s walk through the steps again in the REPL, but this time in more detail\. The function `add` takes a single parameter `a`, and returns a new function that takes a single parameter `b`, and returns the value `a + b`\. Let’s apply `add` to the value `3`, and give the resulting new function a name, `g`\.
nix-repl> g = add 3
The function `g` takes a single parameter and adds `3` to it\. The Nix REPL confirms that `g` is indeed a function\.
nix-repl> :t g a function
Now we can apply `g` to a number to get a new number\.
nix-repl> g 5 8
#### 2\.12\.4\. Multiple parameters using attribute sets
I said earlier that a function in Nix always has a single parameter\. However, that parameter need not be a simple value; it could be a list or an attribute set\. This approach is widely used in Nix, and the language has some special features to support it\. This is an important topic, so we will cover it separately in [Section 2\.13, “Argument sets”](#argument-sets)\.
### 2\.13\. Argument sets
An attribute set that is used as a function parameter is often called an *argument set*\.
#### 2\.13\.1\. Set patterns
To specify an attribute set as a function parameter, we use a *set pattern*, which has the form
{ name1, name2, … }
Note that while the key-value associations in attribute sets are separated by semi-colons, the key names in the attribute set \_pattern are separated by commas\. Here’s an example of a function that has an attribute set as an input parameter\.
nix-repl> greet = { first, last }: “Hello ${first} ${last}! May I call you ${first}?”
nix-repl> greet { first=“Amy”; last=“de Buitléir”; } “Hello Amy de Buitléir! May I call you Amy?”
#### 2\.13\.2\. Optional parameters
We can make some values in an argument set optional by providing default values, using the syntax `*name* ? *value*`\. This is illustrated below\.
nix-repl> greet = { first, last ? “whatever-your-lastname-is”, topic ? “Nix” }: “Hello ${first} ${last}! May I call you ${first}? Are you enjoying learning ${topic}?”
nix-repl> greet { first=“Amy”; } “Hello Amy whatever-your-lastname-is! May I call you Amy? Are you enjoying learning Nix?”
nix-repl> greet { first=“Amy”; topic=“Mathematics”;} “Hello Amy whatever-your-lastname-is! May I call you Amy? Are you enjoying learning Mathematics?”
#### 2\.13\.3\. Variadic attributes
A function can allow the caller to supply argument sets that contain "extra" values\. This is done with the special parameter `…`\.
nix-repl> formatName = { first, last, … }: “${first} ${last}”
One reason for doing this is to allow the caller to pass the same argument set to multiple functions, even though each function may not need all of the values\.
nix-repl> person = { first=“Joe”; last=“Bloggs”; address=“123 Main Street”; }
nix-repl> formatName person “Joe Bloggs”
Another reason for allowing variadic arguments is when a function calls another function, supplying the same argument set\. An example is shown in [Section 2\.13\.4, “@-patterns”](#at-patterns)\.
#### 2\.13\.4\. @-patterns
It can be convenient for a function to be able to reference the argument set as a whole\. This is done using an *@-pattern*\.
nix-repl> formatPoint = p@{ x, y, … }: builtins.toXML p
nix-repl> formatPoint { x=5; y=3; z=2; }
“\n
Alternatively, the @-pattern can appear *after* the argument set, as in the example below\.
nix-repl> formatPoint = { x, y, … } @ p: builtins.toXML p
An @-pattern is the only way a function can access variadic attributes, so they are often used together\. In the example below, the function `greet` passes its argument set, including the variadic arguments, to the function `confirmAddress`\.
nix-repl> confirmAddress = { address, … }: “Do you still live at ${address}?”
nix-repl> greet = args@{ first, last, … }: “Hello ${first}. “ + confirmAddress args
nix-repl> greet person “Hello Joe. Do you still live at 123 Main Street?”
### 2\.14\. If expressions
The conditional construct in Nix is an *expression*, not a *statement*\. Since expressions must have values in all cases, you must specify both the `then` and the `else` branch\.
nix-repl> a = 7
nix-repl> b = 3
nix-repl> if a > b then “yes” else “no” “yes”
### 2\.15\. Let expressions
A `let` expression defines a value with a local scope\.
nix-repl> let x = 3; in x*x 9
nix-repl> let x = 3; y = 2; in x*x + y 11
You can also nest `let` expressions\. The previous expression is equivalent to the following\.
nix-repl> let x = 3; in let y = 2; in x*x + y 11
| | |
| - | - |
| ** | A variable defined inside a `let` expression will "shadow" an outer variable with the same name\.
nix-repl> x = 100
nix-repl> let x = 3; in x*x 9
nix-repl> let x = 3; in let x = 7; in x+1 8
A variable in a let expression can refer to another variable in the expression\. This is similar to how recursive attribute sets work\.
nix-repl> let x = 3; y = x + 1; in x*y 12
### 2\.16\. With expressions
A `with` expression is somewhat similar to a `let` expression, but it brings all of the associations in an attribute set into scope\.
nix-repl> point = { x1 = 3; x2 = 2; }
nix-repl> with point; x1*x1 + x2 11
| | |
| - | - |
| ** | Unlike a `let` expression, a variable defined inside a `with` expression will *not* "shadow" an outer variable with the same name\.
nix-repl> name = “Amy”
nix-repl> animal = { name = “Professor Paws”; age = 10; species = “cat”; }
nix-repl> with animal; “Hello, “ + name “Hello, Amy”
However, you can refer to the variable in the inner scope using the attribute selection operator \(`.`\)\.
nix-repl> with animal; “Hello, “ + animal.name “Hello, Professor Paws”
## 3\. Hello, flake\!
Before learning to write Nix flakes, let’s learn how to use them\. I’ve created a simple example of a flake in this git repository: [https://codeberg\.org/mhwombat/hello-flake](https://codeberg.org/mhwombat/hello-flake)\. To run this flake, you don’t need to install anything; simply run the command below\. The first time you use a flake, Nix has to fetch and build it, which may take time\. Subsequent invocations should be instantaneous\.
$ nix run “git+https://codeberg.org/mhwombat/hello-flake” Hello from your flake!
That’s a lot to type every time we want to use this package\. Instead, we can enter a shell with the package available to us, using the `nix shell` command\.
$ nix shell “git+https://codeberg.org/mhwombat/hello-flake”
In this shell, the command is on our `$PATH`, so we can execute the command by name\.
$ hello-flake Hello from your flake!
Nix didn’t *install* the package; it merely built and placed it in a directory called the “Nix store”\. Thus we can have multiple versions of a package without worrying about conflicts\. We can find out the location of the executable, if we’re curious\.
$ which hello-flake /nix/store/y0i81pxnbrg8jpvqp886b4lrzh7wb0ni-hello-flake/bin/hello-flake
Once we exit that shell, the `hello-flake` command is no longer directly available\.
$ exit $ hello-flake # Fails outside development shell bash: line 24: hello-flake: command not found
However, we can still run the command using the store path we found earlier\. That’s not particularly convenient, but it does demonstrate that the package remains in the store for future use\.
$ /nix/store/y0i81pxnbrg8jpvqp886b4lrzh7wb0ni-hello-flake/bin/hello-flake Hello from your flake!
### 3\.1\. Flake outputs
You can find out what packages and apps a flake provides using the `nix flake show` command\.
$ nix flake show –all-systems git+https://codeberg.org/mhwombat/hello-flake git+https://codeberg.org/mhwombat/hello-flake?ref=refs/heads/main&rev=2d9363f255c44a41be2e5291dd624e078e7f4139 ├───apps │ ├───aarch64-darwin │ │ ├───default: app: no description │ │ └───hello: app: no description │ ├───aarch64-linux │ │ ├───default: app: no description │ │ └───hello: app: no description │ ├───x86_64-darwin │ │ ├───default: app: no description │ │ └───hello: app: no description │ └───x86_64-linux │ ├───default: app: no description │ └───hello: app: no description └───packages ├───aarch64-darwin │ ├───default: package ‘hello-flake’ │ └───hello: package ‘hello-flake’ ├───aarch64-linux │ ├───default: package ‘hello-flake’ │ └───hello: package ‘hello-flake’ ├───x86_64-darwin │ ├───default: package ‘hello-flake’ │ └───hello: package ‘hello-flake’ └───x86_64-linux ├───default: package ‘hello-flake’ └───hello: package ‘hello-flake’
Examining the output of this command, we see that this flake supports multiple architectures \(aarch64-darwin, aarch64-linux, x86\_64-darwin and x86\_64-linux\) and provides both a package and an app called `hello`\.
## 4\. The hello-flake repo
Let’s clone the repository and see how the flake is defined\.
$ git clone https://codeberg.org/mhwombat/hello-flake Cloning into ‘hello-flake’… $ cd hello-flake $ ls flake.lock flake.nix hello-flake LICENSE README.md
This is a simple repo with just a few files\. Like most git repos, it includes `LICENSE`, which contains the software license, and `README.md` which provides information about the repo\.
The `hello-flake` file is the executable we ran earlier\. This particular executable is just a shell script, so we can view it\. It’s an extremely simple script with just two lines\.
hello-flake
1 2 3#!/usr/bin/env sh
echo “Hello from your flake!”
Now that we have a copy of the repo, we can execute this script directly\.
$ ./hello-flake Hello from your flake!
Not terribly exciting, I know\. But starting with such a simple package makes it easier to focus on the flake system without getting bogged down in the details\. We’ll make this script a little more interesting later\.
Let’s look at another file\. The file that defines how to package a flake is always called `flake.nix`\.
flake\.nix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41{ description = “a very simple and friendly flake”;
inputs = { nixpkgs.url = “github:NixOS/nixpkgs”; flake-utils.url = “github:numtide/flake-utils”; };
outputs = { self, nixpkgs, flake-utils }: flake-utils.lib.eachDefaultSystem (system: let pkgs = import nixpkgs { inherit system; }; in { packages = rec { hello = pkgs.stdenv.mkDerivation rec { name = “hello-flake”;
src = ./.;
unpackPhase = “true”;
buildPhase = “:”;
installPhase = ‘’ mkdir -p $out/bin cp $src/hello-flake $out/bin/hello-flake chmod +x $out/bin/hello-flake ‘’; }; default = hello; };
apps = rec { hello = flake-utils.lib.mkApp { drv = self.packages.${system}.hello; }; default = hello; }; } ); }
If this is your first time seeing a flake definition, it probably looks intimidating\. Flakes are written in the Nix language, introduced in [\[\_the\_nix\_language\_\]](#_the_nix_language_)\. However, you don’t really need to know Nix to follow this example\. For now, I’d like to focus on the inputs section\.
inputs = { nixpkgs.url = “github:NixOS/nixpkgs”; flake-utils.url = “github:numtide/flake-utils”; };
There are just two entries, one for `nixpkgs` and one for `flake-utils`\. The first one, `nixpkgs` refers to the collection of standard software packages that can be installed with the Nix package manager\. The second, `flake-utils`, is a collection of utilities that simplify writing flakes\. The important thing to note is that the `hello-flake` package *depends* on `nixpkgs` and `flake-utils`\.
Finally, let’s look at `flake.lock`, or rather, just part of it\.
flake\.lock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41{ “nodes”: { “flake-utils”: { “inputs”: { “systems”: “systems” }, “locked”: { “lastModified”: 1731533236, “narHash”: “sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=”, “owner”: “numtide”, “repo”: “flake-utils”, “rev”: “11707dc2f618dd54ca8739b309ec4fc024de578b”, “type”: “github” }, “original”: { “owner”: “numtide”, “repo”: “flake-utils”, “type”: “github” } }, “nixpkgs”: { “locked”: { “lastModified”: 1757873102, “narHash”: “sha256-kYhNxLlYyJcUouNRazBufVfBInMWMyF+44xG/xar2yE=”, “owner”: “NixOS”, “repo”: “nixpkgs”, “rev”: “88cef159e47c0dc56f151593e044453a39a6e547”, “type”: “github” }, “original”: { “owner”: “NixOS”, “repo”: “nixpkgs”, “type”: “github” } }, “root”: { “inputs”: { “flake-utils”: “flake-utils”, “nixpkgs”: “nixpkgs” } . . .
If `flake.nix` seemed intimidating, then this file looks like an invocation for Cthulhu\. The good news is that this file is automatically generated; you never need to write it\. It contains information about all of the dependencies for the flake, including where they came from, the exact version/revision, and hash\. This lockfile *uniquely* specifies all flake dependencies, \(e\.g\., version number, branch, revision, hash\), so that *anyone, anywhere, any time, can re-create the exact same environment that the original developer used\.*
No more complaints of “but it works on my machine\!”\. That is the benefit of using flakes\.
## 5\. Flake structure
The basic structure of a flake is shown below\.
{ description = package description inputs = dependencies outputs = what the flake produces nixConfig = advanced configuration options }
The `description` part is self-explanatory; it’s just a string\. You probably won’t need `nixConfig` unless you’re doing something fancy\. I’m going to focus on what goes into the `inputs` and `outputs` sections, and highlight some of the things I found confusing when I began using flakes\.
### 5\.1\. Inputs
This section specifies the dependencies of a flake\. It’s an *attribute set*; it maps keys to values\.
To ensure that a build is reproducible, the build step runs in a *pure* environment with no network access\. Therefore, any external dependencies must be specified in the “inputs” section so they can be fetched in advance \(before we enter the pure environment\)\.
Each entry in this section maps an input name to a *flake reference*\. This commonly takes the following form\.
NAME.url = URL-LIKE-EXPRESSION
As a first example of a flake reference, all \(almost all?\) flakes depend on “nixpkgs”, which is a large Git repository of programs and libraries that are pre-packaged for Nix\. We can write that as
nixpkgs.url = “github:NixOS/nixpkgs/nixos-version”;
where *version* is replaced with the version number that you used to build the package, e\.g\. `22.11`\. Information about the latest nixpkgs releases is available at [https://status\.nixos\.org/](https://status.nixos.org/)\. You can also write the entry without the version number
nixpkgs.url = “github:NixOS/nixpkgs/nixos”;
or more simply,
nixpkgs.url = “nixpkgs”;
You might be concerned that omitting the version number would make the build non-reproducible\. If someone else builds the flake, could they end up with a different version of nixpkgs? No\! remember that the lockfile \(`flake.lock`\) *uniquely* specifies all flake inputs\.
Git and Mercurial repositories are the most common type of flake reference, as in the examples below\.
A Git repository
`git+https://github.com/NixOS/patchelf`
A specific branch of a Git repository
`git+https://github.com/NixOS/patchelf?ref=master`
A specific revision of a Git repository
`git+https://github.com/NixOS/patchelf?ref=master&rev=f34751b88bd07d7f44f5cd3200fb4122bf916c7e`
A tarball
`[https://github\.com/NixOS/patchelf/archive/master\.tar\.gz](https://github.com/NixOS/patchelf/archive/master.tar.gz)`
| | |
| - | - |
| ** | Although you probably won’t need to use it, there is another syntax for flake references that you might encounter\. This example
inputs.import-cargo = { type = “github”; owner = “edolstra”; repo = “import-cargo”; };
is equivalent to
inputs.import-cargo.url = “github:edolstra/import-cargo”;
Each of the `inputs` is fetched, evaluated and passed to the `outputs` function as a set of attributes with the same name as the corresponding input\.
### 5\.2\. Outputs
This section is a function that essentially returns the recipe for building the flake\.
We said above that `inputs` are passed to the `outputs`, so we need to list them as parameters\. This example references the `import-cargo` dependency defined in the previous example\.
outputs = { self, nixpkgs, import-cargo }: { definitions for outputs };
So what actually goes in the highlighted section? That depends on the programming languages your software is written in, the build system you use, and more\. There are Nix functions and tools that can simplify much of this, and new, easier-to-use ones are released regularly\. We’ll look at some of these in the next section\.
## 6\. A generic flake
The previous section presented a very high-level view of flakes, focusing on the basic structure\. In this section, we will add a bit more detail\.
Flakes are written in the Nix programming language, which is a functional language\. As with most programming languages, there are many ways to achieve the same result\. Below is an example you can follow when writing your own flakes\. I’ll explain the example in some detail\.
{ description = “brief package description”;
inputs = { nixpkgs.url = “github:NixOS/nixpkgs”; flake-utils.url = “github:numtide/flake-utils”; …other dependencies… ❶ };
outputs = { self, nixpkgs, flake-utils, …other dependencies… ❷ }: flake-utils.lib.eachDefaultSystem (system: ❸ let pkgs = import nixpkgs { inherit system; }; python = pkgs.python3; in { devShells = rec { default = pkgs.mkShell { packages = [ packages needed for development shell; ❹ ])) ]; };
packages = rec { myPackageName = package definition; ❺ default = myPackageName; };
apps = rec { myPackageName = flake-utils.lib.mkApp { drv = self.packages.${system}.myPackageName; }; default = myPackageName; }; } ); }
We discussed how to specify flake inputs `❶` in the previous section, so this part of the flake should be familiar\. Remember also that any dependencies in the input section should also be listed at the beginning of the outputs section `❷`\.
Now it’s time to look at the content of the output section\. If we want the package to be available for multiple systems \(e\.g\., “x86\_64-linux”, “aarch64-linux”, “x86\_64-darwin”, and “aarch64-darwin”\), we need to define the output for each of those systems\. Often the definitions are identical, apart from the name of the system\. The eachDefaultSystem function `❸` provided by flake-utils allows us to write a single definition using a variable for the system name\. The function then iterates over all default systems to generate the outputs for each one\.
The `devShells` variable specifies the environment that should be available when doing development on the package\. If you don’t need a special development environment, you can omit this section\. At `❹` you would list any tools \(e\.g\., compilers and language-specific build tools\) you want to have available in a development shell\. If the compiler needs access to language-specific packages, there are Nix functions to assist with that\. These functions are very language-specific, and not always well-documented\. We will see examples for some languages later in the tutorial\. In general, I recommend that you do a web search for "nix *language-name*", and try to find resources that were written or updated recently\.
The `packages` variable defines the packages that this flake provides\. The package definition `❺` depends on the programming languages your software is written in, the build system you use, and more\. There are Nix functions and tools that can simplify much of this, and new, easier-to-use ones are released regularly\. Again, I recommend that you do a web search for "nix *language-name*", and try to find resources that were written or updated recently\.
The `apps` variable identifies any applications provided by the flake\. In particular, it identifies the default executable ❻ that `nix run` will run if you don’t specify an app\.
Below is a list of some functions that are commonly used in this section\.
General-purpose
The standard environment provides `mkDerivation`, which is especially useful for the typical `./configure; make; make install` scenario\. It’s customisable\.
Python
`buildPythonApplication`, `buildPythonPackage`\.
Haskell
`mkDerivation` \(Haskell version, which is a wrapper around the standard environment version\), `developPackage`, `callCabal2Nix`\.
## 7\. Another look at hello-flake
Now that we have a better understanding of the structure of `flake.nix`, let’s have a look at the one we saw earlier, in the `hello-flake` repo\. If you compare this flake definition to the colour-coded template presented in [Chapter 6, A generic flake](#_a_generic_flake), most of it should look familiar\.
flake\.nix
{ description = “a very simple and friendly flake”;
inputs = { nixpkgs.url = “github:NixOS/nixpkgs”; flake-utils.url = “github:numtide/flake-utils”; };
outputs = { self, nixpkgs, flake-utils }: flake-utils.lib.eachDefaultSystem (system: let pkgs = import nixpkgs { inherit system; }; in { packages = rec { hello = . . . SOME UNFAMILIAR STUFF . . . }; default = hello; };
apps = rec { hello = flake-utils.lib.mkApp { drv = self.packages.${system}.hello; }; default = hello; }; } ); }
This `flake.nix` doesn’t have a `devShells` section, because development on the current version doesn’t require anything beyond the “bare bones” linux commands\. Later we will add a feature that requires additional development tools\.
Now let’s look at the section I labeled `SOME UNFAMILIAR STUFF` and see what it does\.
packages = rec { hello = pkgs.stdenv.mkDerivation rec { ❶ name = “hello-flake”;
src = ./.; ❷
unpackPhase = “true”;
buildPhase = “:”;
installPhase = ‘’ mkdir -p $out/bin ❸ cp $src/hello-flake $out/bin/hello-flake ❹ chmod +x $out/bin/hello-flake ❺ ‘’; };
This flake uses `mkDerivation` `❶` which is a very useful general-purpose package builder provided by the Nix standard environment\. It’s especially useful for the typical `./configure; make; make install` scenario, but for this flake we don’t even need that\.
The `name` variable is the name of the flake, as it would appear in a package listing if we were to add it to Nixpk