nh (nix helper)
nh is a nix helper and it’s extremely powerful. We’ll be using it (in conjunction with nix-output-monitor) to give up more detail about our nix-related build processes as well as provide a way to clean out the nix store.
Installation
Section titled “Installation”With all things nix, there’s a miriad of ways to install and use nh. Here’s how I do it:
first, add the nh input:
{ inputs = { ... nh = { url = "github:nix-community/nh"; inputs.nixpkgs.follows = "nixpkgs"; }; };}create a file called nh.nix and import it somewhere for your current system:
{ inputs, pkgs, ...}: { environment.systemPackages = with pkgs; [ inputs.nh.packages.${system}.default ];}{ imports = [ ./hardware-configuration.nix ../relative_path_to/nh.nix ]; ... rest of your config}You can also just grab the nh package from nixpkgs (but I don’t recommend it since doing it the first way allows us to individually update nh in the future if we’d like to):
{ inputs, pkgs, ...}: { environment.systemPackages = with pkgs; [ inputs.nh.packages.${system}.default nh ];}We discussed the os function briefly in the previous section - mostly just hinting at it’s existence. nh automatically assumes we’re using flakes. An example of a NixOS configuration rebuild with nh looks like this:
nh os switch /home/<your-username>/nixosHere’s a description of all the nh os subcommands related to rebuilding NixOS configurations:
nh os boot: Create a new NixOS configuration, do not switch to it, and add it as a boot entry.nh os switch: Create a new NixOS configuration, switch to it, and add it as a boot entry.nh os test: Create a new NixOS configuration, switch to it, and do not add it as a boot entry.
nh os automatically detects the current hostname and so it can automatically target the correct configuration. If you’re using a different hostname, you can specify it with the -H flag.
There are more nh os subcommands, but they’re not relevant to this article.
nh clean
Section titled “nh clean”The nh clean subcommand is used to clean up the nix store. More details about the nix store can be found on the reference page for nix-store.
We can setup a cleaning job to occur automatically everytime we do a rebuild of our NixOS configuration.
{ inputs, pkgs, ...}: { environment.systemPackages = with pkgs; [ inputs.nh.packages.${system}.default ]; programs.nh = { enable = true; clean.enable = true; clean.extraArgs = "--keep-since 3d --keep 3"; flake = "/home/<your-username>/nixos"; };}will set up a cleaning job that will keep the last 3 days worth and a minimum of the last 3 system derivations.