Low-level derivations
Writing low-level derivations without the convenience of the Standard environment requires understanding the core fundamentals of how Nix works. While writing derivations in this manner is not common, they can be useful when no utility present in the standard environment matches the required use case, as well as being an essential learning tool for understanding why stdenv.mkDerivation
is needed in most cases.
In the section below, we'll start by writing a simple derivation that creates a script which displays the message "Hello, world" when run. While developing the Nix file, we'll be encountering the same challenges that led the Nix community to develop more ergonomic tooling. Each obstacle we hit - from missing system dependencies to path management - illustrates a core principle of Nix's purely functional build model. By the end, you'll understand both what makes Nix powerful and why most derivations use abstraction layers.
A Hello, world example
Our goal is simple: creating a script that displays "Hello, world!". If we were to simply create a script ourselves, it might look like this:
#!/bin/bash
echo "Hello, world!"
When running this script (e.g. $ ./example.sh
) we'll get exactly the output we want. However, we're trying to build the script using Nix. Our first approach might be to write a simple derivation similar to:
derivation {
name = "hello-world";
system = builtins.currentSystem;
builder = "/bin/sh";
args = [
"-c"
"echo 'Hello, World!' > $out"
];
}